views:

96

answers:

2

A cut down version of my code sort of looks like this:

string="test test testtest testtest test";
replacer="test";
string=string.replace(new RegExp(' '+replacer+' ','gi')," REPLACED ");

Now, I want to replace a word only if there's a space surrounding it, The code actually works fine but I'm just wondering why the one below which would be better in my case doesn't work.

RegExp('\s'+replacer+'\s','gi')
+3  A: 

Why don't you try this:

RegExp('\\s'+replacer+'\\s','gi')
Breton
+1, since `'\s' == 's'`
CMS
Awesome, RegExp('\\s'+replacer+'\\s','gi') worked like a charm.
Dean
A: 

Your example will replace tabs with spaces.

You probably want this:

string=string.replace(new RegExp('\\b'+replacer+'\\b','gi'),"REPLACED");

Or, if you really want only whitespace to separate words, then you could use something like this:

string=string.replace(new RegExp('(\\s)'+replacer+'(\\s)','gi'),"$1REPLACED$2");
Jeremy Stein
Alan Moore
Thank you, Alan. I guess if the OP wants to keep the same whitespace he'll need to capture it and use backrerefences in the replace text. I'll update my example.
Jeremy Stein