根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
当前回答
使用
str = str.replace(new RegExp("abc", 'g'), "");
因此,新的RegExp(“abc”,“g”)创造了一个常见的表达,符合所有事件(“g”旗帜)的文本(“abc”)。第二部分是什么被取代,在你的情况下,空线(“). str 是线,我们必须将它,作为替代(...)只是返回结果,但不超过。
其他回答
我知道这不是最好的办法,但你可以尝试一下:
var annoyingString = "Test abc test test abc test test test abc test test abc";
while (annoyingString.includes("abc")) {
annoyingString = annoyingString.replace("abc", "")
}
2019年11月,新功能被添加到JavaScript, string.prototype.replaceAll()。
目前它仅支持巴比伦,但也许在未来它可以在所有浏览器中实施。
这是最快的版本,不使用常规表达式。
修订 JSperf
replaceAll = function(string, omit, place, prevstring) {
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return replaceAll(prevstring, omit, place, string)
}
它几乎比分裂和合并方法快两倍。
正如在评论中所指出的那样,如果你的错误变量包含位置,就不会工作,因为它总是能够取代另一个出现的词。
有另一个JSperf与我的回归替换的变量,它走得更快(http://jsperf.com/replace-all-vs-split-join/12)!
2017 年 7 月 27 日更新: 看起来 RegExp 现在在最近发布的 Chrome 59 中具有最快的性能。
String.prototype.replace 所有 - ECMAScript 2021
新的 String.prototype.replaceAll() 方法将返回一个新的行,一个模式的所有比赛被替换。
const message = 'dog barks meow meow'; const messageFormatted = message.replaceAll('meow', 'woof') console.log(messageFormatted);
以前的答案太复杂了,只需使用替代功能如下:
str.replace(/your_regex_pattern/g, replacement_string);
例子:
var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var res = str.replace(/[abc]+/g, ""); console.log(res);