Created
February 21, 2011 09:07
-
-
Save jacksenechal/836837 to your computer and use it in GitHub Desktop.
JavsScript word scrambler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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