根據一條線:

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

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

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

如何替代所有事件?


当前回答

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

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

其他回答

我在“图书馆”部分中添加了下面的功能到这个性能测试页面:

首頁 〉外文書 〉文學 〉文學 〉WEB

function _replace(t, s, r){
    var i = t.indexOf(s);
    if (i == -1) return t;
    return t.slice(0, i) + r + _replace(t.slice(i + s.length, t.length), s,r);
}

把它当作测试:

var replaced = _replace(testString, 'abc', '123');

想法的一部分是,如果链条不太大,它可能会在CPU存储库中结束;通过它并粘贴它的碎片将这些比特放入存储库中,然后搜索可以完全使用CPU存储数据运行。

这不是尽可能快的,但它是尽可能快的,我可以管理没有可转换的线条. 在JavaScript中的线条可能有一个指标每个元素,因此,一个解决方案涉及很多线条元素是不可能像CPU缓存友好。

这个解决方案结合了一些以前的答案,并更好地符合建议的2020年8月标准解决方案,这个解决方案在2020年9月对我来说仍然可行,因为String.replaceAll不在我使用的Node.js二进制中。


RegExp.escape 是一个单独的问题处理,但它在这里很重要,因为官方提出的解决方案将自动逃脱基于链条的查找输入。


如果你需要准确的标准符合,对于一个应用程序,它是严格依赖于标准实施,那么我建议使用Babel或其他工具,你得到“正确的答案”每次而不是Stack Overflow。


代码:

if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {
  RegExp.escape = function(string) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
    // https://github.com/benjamingr/RegExp.escape/issues/37
    return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  };
}

if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
  String.prototype.replaceAll = function(find, replace) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
    // If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
    // TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
    // String parameters to 'find' do not require special handling.
    // Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
    // Does not conform to "Specifying a function as a parameter" for replace
    return this.replace(
          Object.prototype.toString.call(find) == '[object RegExp]' ?
            find :
            new RegExp(RegExp.escape(find), 'g'),
          replace
        );
  }
}

编码,小型:

Object.prototype.hasOwnProperty.call(RegExp,"escape")||(RegExp.escape=function(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}),Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(RegExp.escape(e),"g"),t)});

例子:

console.log(
  't*.STVAL'
    .replaceAll(
      new RegExp(RegExp.escape('T*.ST'), 'ig'),
      'TEST'
    )
);

console.log(
  't*.STVAL'
    .replaceAll(
      't*.ST',
      'TEST'
    );
);

没有 RegExp.Escape 的代码:

if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
  String.prototype.replaceAll = function(find, replace) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
    // If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
    // TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
    // String parameters to 'find' do not require special handling.
    // Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
    // Does not conform to "Specifying a function as a parameter" for replace
    return this.replace(
          Object.prototype.toString.call(find) == '[object RegExp]' ?
            find :
            new RegExp(find.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g'),
          replace
        );
  }
}

代码没有 RegExp.Escape,小型:

Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),"g"),t)});

最简单的解决方案 -

let str = "Test abc test test abc test test test abc test test abc"; str = str.split(" "); str = str.filter((ele, key)=> ele!=="abc") str = str.join(" ")

或者只是 -

str = str.split(““)。过滤器(ele,键) => ele!=“abc”).加入(““)

点击此处,我肯定会帮助你:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search and replace for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
  var str = 'Is this "3" dris "3"?';
  var allvar= '"3"';
  var patt1 = new RegExp( allvar, 'g' );
  document.getElementById("demo").innerHTML = str.replace(patt1,'"5"');
}
</script>
</body>
</html>

这里是JSFiddle的链接。

String.prototype.replace 所有 - ECMAScript 2021

新的 String.prototype.replaceAll() 方法将返回一个新的行,一个模式的所有比赛被替换。

const message = 'dog barks meow meow'; const messageFormatted = message.replaceAll('meow', 'woof') console.log(messageFormatted);