gpt4 book ai didi

javascript - 如何替换字符串中的 "is"等单词,而不影响 "Pakistani"|节点js

转载 作者:行者123 更新时间:2023-11-28 11:14:47 25 4
gpt4 key购买 nike

如何在Nodejs中替换单词,例如如果我想替换单词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

最佳答案

使用单词边界,并搜索模式\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);

关于javascript - 如何替换字符串中的 "is"等单词,而不影响 "Pakistani"|节点js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56816099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com