我正在寻找一个 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"
另外,如果我输入一个不匹配的字符串,你可以看到会发生什么:
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
如果你想替换句子但保留相同的标点符号:
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?
关于javascript - 找到短语时替换整个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414730/