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

标签 javascript regex

我正在寻找一个 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/

相关文章:

regex - 尽管输入了 10 位数字的正则表达式,但输入的手机号码值仍显示 "not a valid number"

python - 在正则表达式 python 中更改行

javascript - Photoshop 脚本 (JS) : Duplicate layer set and subs

javascript - 我试图在谁赢谁输的答案弹出之前延迟(剪刀石头布游戏)

regex - 删除R中两种字符串模式之间的字母

javascript - 正则表达式匹配除模式之外的所有内容

c++ - BOOST 正则表达式全局搜索行为

javascript - 如何使用dygraphs打印非时间序列

javascript - 如何将函数/事件监听器添加到使用 ES6 模板文字创建的元素?

javascript - Android native 通过 cordova 进行 JavaScript 通信