在JavaScript中替换字符串/字符的所有实例的最快方法是什么?while, for循环,正则表达式?


当前回答

I tried a number of these suggestions after realizing that an implementation I had written of this probably close to 10 years ago actually didn't work completely (nasty production bug in an long-forgotten system, isn't that always the way?!)... what I noticed is that the ones I tried (I didn't try them all) had the same problem as mine, that is, they wouldn't replace EVERY occurrence, only the first, at least for my test case of getting "test....txt" down to "test.txt" by replacing ".." with "."... maybe I missed so regex situation? But I digress...

因此,我重写了我的实现如下。这是非常简单的,虽然我怀疑不是最快的,但我也不认为现代JS引擎的区别是重要的,除非你在一个紧密的循环中做这件事,但这总是任何事情的情况…

function replaceSubstring(inSource, inToReplace, inReplaceWith) {

  var outString = inSource;
  while (true) {
    var idx = outString.indexOf(inToReplace);
    if (idx == -1) {
      break;
    }
    outString = outString.substring(0, idx) + inReplaceWith +
      outString.substring(idx + inToReplace.length);
  }
  return outString;

}

希望这能帮助到别人!

其他回答

使用String对象的replace()方法。

正如所选答案中提到的,应该在正则表达式中使用/g标志,以便替换字符串中子字符串的所有实例。

var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");

newString现在是'Thas as a strange '

你也可以试试:

string.split('foo').join('bar');

我不知道最快的是什么,但我知道最易读的是什么——最短最简单的是什么。即使它比其他溶液慢一点,也值得使用。

所以使用:

 "string".replace("a", "b");
 "string".replace(/abc?/g, "def");

享受好的代码而不是更快的速度(嗯…1/100000秒不是差)和丑陋的差。;)

最简单的方法是使用带有g标志的正则表达式来替换所有实例:

str.replace(/foo/g, "bar")

这将把字符串str中出现的所有foo替换为bar。如果你只有一个字符串,你可以像这样将它转换为RegExp对象:

var pattern = "foobar",
    re = new RegExp(pattern, "g");