Skip to content

Instantly share code, notes, and snippets.

@jacksenechal
Created February 21, 2011 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacksenechal/836837 to your computer and use it in GitHub Desktop.
Save jacksenechal/836837 to your computer and use it in GitHub Desktop.
JavsScript word scrambler
/* Called on document.ready */
$(function () {
$("body *").replaceText(/\b([A-z]{4,})\b/g, scramble_inner );
});
/* Scramble the inner characters of a word */
function scramble_inner(word) {
return word[0]
+ force_shuffle(word.slice(1, word.length - 1))
+ word[word.length - 1];
}
/* Randomize characters in the string, but check to make sure
* they're different from the original. Handle's the special
* case where all inner characters are equal, for instance "moooo".
*/
function force_shuffle(str) {
if (all_chars_same(str)) return str;
var result = str;
while (str === result) {
result = str.split('').sort(function() {
return Math.floor(Math.random() * 2) ? 1 : -1;
}).join('');
}
return result;
}
/* Check whether all characters in the string are equal, eg "ooo" */
function all_chars_same(str) {
for (i = 0; i < str.length; i++) {
if (str[i] !== str[0]) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment