根據一條線:

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

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

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

如何替代所有事件?


当前回答

在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代码的良好实践。

其他回答

我的实践,非常自我解释

function replaceAll(string, token, newtoken) {
    if(token!=newtoken)
    while(string.indexOf(token) > -1) {
        string = string.replace(token, newtoken);
    }
    return string;
}

看看这个答案,也许它会帮助,我在我的项目中使用它。

function replaceAll(searchString, replaceString, str) {
    return str.split(searchString).join(replaceString);
}

replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test  test test  test test test  test test "

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

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

方法1

尝试执行一个常见的表达式:

“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试

方法2

与ABC分开并加入空空间。

“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试

你可以尝试这样:

示例数据:

var text = "heloo,hai,hei"

text = text.replace(/[,]+/g, '')

text.forEach((value) => {
  hasil = hasil.replace(',', '')
})