views:

114

answers:

2

Alright, here's my current test function:

function make_void( str )
{
 var str_arr = str.split( /[\W]+/ );
 var voidstr;
 var newstr = "";

 for ( var i = 0; i < str_arr.length; i++ )
 {
  voidstr = str_arr[i];
  // if ( Math.random() <= 0.9 )
  // {
   voidstr = voidstr.replace( /\w/gi, "?" );
  // }

  newstr += voidstr + " ";
 }

 document.writeln( newstr );
}

The problem? Punctuations is lost.

What's a good way to revise that such that they aren't?

+1  A: 

Some sample text of what you're trying to match against might help. (What do you actually want to keep?)

For now, the following regex might help:

[\w\d,.?:;"'-()]

This matches words, digits, and a number of punctuation characters (though by no means all).

Noldorin
+3  A: 

Split on whitespace (\s) not on non-word (\W) and you will retain punctuation.

function make_void( str )
{
        var str_arr = str.split( /\s+/ ); //  !!!THIS LINE CHANGED!!!
        var voidstr;
        var newstr = "";

        for ( var i = 0; i < str_arr.length; i++ )
        {
                voidstr = str_arr[i];
                // if ( Math.random() <= 0.9 )
                // {
                        voidstr = voidstr.replace( /\w/gi, "?" );
                // }

                newstr += voidstr + " ";
        }

        document.writeln( newstr );
}


update: example snippet using Array.join() method:

for ( var i = 0; i < str_arr.length; i++ )
{
 // if ( Math.random() <= 0.9 )
 // {
  str_arr[i] = str_arr[i].replace( /\w/gi, "?" );
 // }
}

var newstr = str_arr.join(' ');
Peter Boughton
good point, no pun intended :)
Vinko Vrsalovic
Oh! Duh! I knew there was an easy answer to this. :P
Daddy Warbox
Oh, and another thought - consider using Array.join(' ') instead of manual string concatentation - I think it would be faster, and I'd certainly say it's more readable...
Peter Boughton