如何在字符串中替换“ is”之类的单词,而又不影响“ Pakistani”节点js

时间:2019-06-29 08:23:10

标签: javascript string replace

如何在Node.js中替换单词,例如,如果我想将字符串下方的单词is替换为done

He is a Pakistani and is a good person

输出仅给出:

He done a pakdonetani and done a good person而不是He done a Pakistani and done a good person。 我正在使用此代码:

var str = "He is a Pakistani and is a good person";
var res = str.replace(/is/g, "done");
console.log(res);

可以这样说,相反:

var res = str.replace(/ is /g, "done");

但此字符串将失败:

var str = "He is a Pakistani and a good person he is.";

为应对这种情况,我们可以:

var res = str.replace(/ is/g, "done");

但是它将失败

var str = "He is a Pakistani, and furthur added 'is a good boy'"

如果我们这样做:

var res = str.replace(/ is/g, "done");
var res = res.replace(/is /g,"done ");

然后在这种情况下失败:

var str = "He is a Pakistani, and furthur added 'is a good boy and a caring boy he is'. Besides he said that he lives on an island";

因为它提供了输出:

Hedone a Pakistani, and furthur added 'done a good boy and a caring boy hedone'. Besides he said that he lives on andoneland

1 个答案:

答案 0 :(得分:10)

使用单词边界,并搜索模式\bis\b

var str = "He is a Pakistani, and furthur added 'is a good boy'"
var res = str.replace(/\bis\b/g, "done");
console.log(res);