gpt4 book ai didi

javascript - 找到短语时替换整个句子

转载 作者:行者123 更新时间:2023-11-30 12:57:57 25 4
gpt4 key购买 nike

我正在寻找一个 JavaScript 正则表达式,它会在句子中查找一个短语,例如“seem to be new”,如果找到那个短语,它会用“seem”替换整个句子。所以下面所有的句子都会被“seem”代替

How do I get rid of the "You seem to be new" message?
How do I get kill the "You seem to be new" message?
How do I stop the "You seem to be new" message from appearing?

最佳答案

这是您要找的吗?

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*[?!.]/g,"seem");
console.log(str); // "seemseemseem"

Fiddle

另外,如果我输入一个不匹配的字符串,你可以看到会发生什么:

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? This sentence doesn\'t seem to contain your phrase. How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*[?!.]/g,"seem");
console.log(str); //seemseem This sentence doesn't seem to contain your phrase.seem

Fiddle

如果你想替换句子但保留相同的标点符号:

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? This sentence doesn\'t seem to contain your phrase. How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*([?!.])/g," seem$1");
console.log(str); // seem? seem? This sentence doesn't seem to contain your phrase. seem?

Fiddle

关于javascript - 找到短语时替换整个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414730/

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