根據一條線:

s = "Test abc test test abc test test test abc test test abc";

这似乎只是在上面的行中删除ABC的第一次出现:

s = s.replace('abc', '');

如何替代所有事件?


当前回答

我知道这不是最好的办法,但你可以尝试一下:

var annoyingString = "Test abc test test abc test test test abc test test abc";

while (annoyingString.includes("abc")) {
    annoyingString = annoyingString.replace("abc", "")
}

其他回答

要编码一个URL,你不应该只考虑空间,而是用编码URI正确地转换整个行。

encodeURI("http://www.google.com/a file with spaces.html")

要得到:

http://www.google.com/a%20file%20with%20spaces.html

从 v85 开始,Chrome 现在支持 String.prototype.replaceAll 原始。 请注意,这一点超越了所有其他提议的解决方案,并且应该使用一次主要支持。

功能状态: https://chromestatus.com/feature/6040389083463680

var s = “Hello hello world”; s = s.replaceAll(“Hello”,“”); // s 现在是“世界” console.log(s)

function replaceAll(str, find, replace) {
    var $r="";
    while($r!=str){ 
        $r = str;
        str = str.replace(find, replace);
    }
    return str;
}

以前的答案太复杂了,只需使用替代功能如下:

str.replace(/your_regex_pattern/g, replacement_string);

例子:

var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var res = str.replace(/[abc]+/g, ""); console.log(res);

我只是想分享我的解决方案,基于JavaScript最新版本的一些功能功能:

   var str = "Test abc test test abc test test test abc test test abc";

   var result = str.split(' ').reduce((a, b) => {
      return b == 'abc' ? a : a + ' ' + b;   })

  console.warn(result)