根據一條線:

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

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

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

如何替代所有事件?


当前回答

我的实践,非常自我解释

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

其他回答

2019年11月,新功能被添加到JavaScript, string.prototype.replaceAll()。

目前它仅支持巴比伦,但也许在未来它可以在所有浏览器中实施。

试试这:

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

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

    return str;
};

这是最快的版本,不使用常规表达式。

修订 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 中具有最快的性能。

我使用p来存储以前的回归替换结果:

function replaceAll(s, m, r, p) {
    return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}

它将取代链 s 的所有事件,直到它是可能的:

replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'

要避免无限旋转,我检查替代r是否包含一匹匹匹配m:

replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'
str = str.replace(/abc/g, '');

或者尝试替代所有方法,如本答案所建议:

str = str.replaceAll('abc', '');

或:

var search = 'abc';
str = str.replaceAll(search, '');

EDIT: 关于更换的澄清 所有可用性

替代All 方法将添加到 String 的原型,这意味着它将适用于所有 String 对象/字体。

例子:

var output = "test this".replaceAll('this', 'that'); // output is 'test that'.
output = output.replaceAll('that', 'this'); // output is 'test this'