Dean
Dean

Reputation: 53

Javascript - replacing a word using regexp only if there's a space around it

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')

Upvotes: 0

Views: 1187

Answers (3)

Arcsoftech
Arcsoftech

Reputation: 21

I have tried many thing but no regex pattern worked perfectly.

My problem was I had to replace "it" with <product_name> in sentence.

For example,"what is use of it" => "what is use of <product_name>"

But in the words like acidity,regex pattern changes it to "acid<product_name>y" which is wrong.

I came up with one solution which solved my problem and would like to share it with you all.

var b=[];
var sent="what is use of it";
sent.split(" ").forEach((x) => {if(x=='it'){x=<product_name>;}b.push(x)});
sent=b.join(" ");

Upvotes: 0

Jeremy Stein
Jeremy Stein

Reputation: 19661

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");

Upvotes: 2

Breton
Breton

Reputation: 15592

Why don't you try this:

RegExp('\\s'+replacer+'\\s','gi')

Upvotes: 3

Related Questions