View Single Post
  #4 (permalink)  
Old June 26th, 2008, 05:24 PM
Old Pedant Old Pedant is offline
Friend of Wrox
 
Join Date: Jun 2008
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Okay, it took over 20 minutes. Mainly because I started playing with the problem of punctuation. But I decided, finally, to leave that to you. As is, this code treats *ALL* non-space characters as letters in a word. So punctuation immediately following a word becomes part of the word. Meaning that it can scramble
     framitz.
into
     fzimrat.
retaining the f and the period, instead of the f and the z.

Also, line breaks are lost and treated the same as spaces.

So...room for improvement, for sure. But still fun.

Just save this to a file named "mungeText.html" on your machine and then browse to that file with your browser.

Code:
<HTML><BODY>
<FORM>
Enter some text:<br/>
<TEXTAREA Name="raw" style="width: 500px; height: 200px;">
'Twas brillig and the slithy toves 
Did gyre and gymbal in the wabe 
All mimsy were the borogoves  
and the mome rath outgrabe 
</TEXTAREA>
<P>
<input type=button value="&quot;Translate&quot;" onClick="translate(this.form.raw);">
</FORM>

Translation:<br/>
<DIV id="munged"></DIV>

<script language="javascript">
function mungeWord( word )
{
    var i;
    var letters = new Array();
    for ( i = 0; i < word.length; ++i )
    {
        letters[i] = word.charAt(i);
    }
    var rlen = letters.length - 2;
    for ( i = 1; i < letters.length-1; ++i )
    {
        var rnum = 1 + Math.floor( Math.random() * rlen );
        var temp = letters[i];
        letters[i] = letters[rnum];
        letters[rnum] = temp;
    }
    return letters.join("");
}

function translate( fld )
{
    var words = fld.value.split(/\s/);
    for ( var w = 0; w < words.length; ++w )
    {
        var word = words[w];
        if ( word.length > 3 ) words[w] = mungeWord(word);
    }
    document.getElementById("munged").innerHTML = words.join(" ");
}
</script>
</body></HTML>
Reply With Quote