开发者

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

开发者 https://www.devze.com 2022-12-13 02:04 出处:网络
A cut down version of my code sort of looks like this: string=\"test test testtest testtest test\"; replacer=\"test\";

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 wor开发者_JAVA技巧d 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')


Why don't you try this:

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消