Scramble a word

Text Javascript

According to research at an English university, the order of letters in a word is not important for the text to be readable, the only requirement would be that the first and last letter of each word are kept in the right place. The rest can be a complete mess and still be readable. The researchers believe this is because we do not read every letter individually but rather the word as a whole.

The origin of this discovery appears to be this paper by Graham Rawlinson of Nottingham University in 1976.

The scrambler

Enter a sample piece of text and press the 'Scramble!' button to see it get scrambled before your eyes. With the button in focus, keep the 'Enter' key pressed for an even scramblier effect.

The script

The scramble function is really nothing more than a single call to the replace method of the string argument s. The replacement string is however constructed in an inner function that employs three local variables in addition to its four parameters t, a matched word, consisting of a, its first character, b, the middle part, and the last letter c. The middle part is split along all matches to the regular expression pattern /\B/, which matches at the position between two word characters, and since b by definition consists of all word characters, the result is an array of single characters. This array is shuffled in a for loop, then joined back to a string and returned with the first and last letters attached at the ends.

Mouse over or double-click the script elements for more detailed highlighting.

function scramble( s ) {
 return s.replace(
  function( t, a, b, c ) {
   b = b.split( /\B/ );
   for( var i = b.length, j, k; i; j = parseInt( Math.random() * i ),
    k = b[--i], b[i] = b[j], b[j] = k ) {}
   return a + b.join( '' ) + c;

document.forms.f.onsubmit = function() {
 this.elements.t.value = scramble( this.elements.t.value );
 return false;

document.forms.f.elements.t.value =
 scramble( gettext( document.getElementsByTagName( 'p' )[0] ) );