根據一條線:

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

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

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

如何替代所有事件?


当前回答

while (str.indexOf('abc') !== -1)
{
    str = str.replace('abc', '');
}

其他回答

所有答案都被接受,你可以以多种方式做到这一点。

const str = “测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试

试试这:

String.prototype.replaceAll = function (sfind, sreplace) {
    var str = this;

    while (str.indexOf(sfind) > -1) {
        str = str.replace(sfind, sreplace);
    }

    return str;
};

对抗全球常规表达:

anotherString = someString.replace(/cat/g, 'dog');

如果使用图书馆是您的选择,那么您将获得与图书馆功能一起进行的测试和社区支持的好处。

// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;

在JavaScript中使用RegExp可以为您完成工作,只需在下面的代码中做一些类似的事情,不要忘记 /g 之后是全球性的:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replace(/abc/g, '');

如果你想重复使用,创建一个功能来为你做到这一点,但它不推荐,因为它只是一个线功能。

String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
  return this.replace(new RegExp(string, 'g'), replaced);
};

并简单地使用它在你的代码上和上如下:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');

但是,正如我之前提到的那样,它不会在写字或性能方面产生巨大的差异. 只有加密功能可能会影响长线上的某些更快的性能,如果您想要重新使用,则是DRY代码的良好实践。