在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;

}

希望这能帮助到别人!

其他回答

我认为真正的答案是,这完全取决于你的输入是什么样的。我创建了一个JsFiddle来尝试这些方法,并针对各种输入创建了自己的JsFiddle。无论我如何看待这些结果,我都看不到明显的赢家。

RegExp wasn't the fastest in any of the test cases, but it wasn't bad either. Split/Join approach seems fastest for sparse replacements. This one I wrote seems fastest for small inputs and dense replacements: function replaceAllOneCharAtATime(inSource, inToReplace, inReplaceWith) { var output=""; var firstReplaceCompareCharacter = inToReplace.charAt(0); var sourceLength = inSource.length; var replaceLengthMinusOne = inToReplace.length - 1; for(var i = 0; i < sourceLength; i++){ var currentCharacter = inSource.charAt(i); var compareIndex = i; var replaceIndex = 0; var sourceCompareCharacter = currentCharacter; var replaceCompareCharacter = firstReplaceCompareCharacter; while(true){ if(sourceCompareCharacter != replaceCompareCharacter){ output += currentCharacter; break; } if(replaceIndex >= replaceLengthMinusOne) { i+=replaceLengthMinusOne; output += inReplaceWith; //was a match break; } compareIndex++; replaceIndex++; if(i >= sourceLength){ // not a match break; } sourceCompareCharacter = inSource.charAt(compareIndex) replaceCompareCharacter = inToReplace.charAt(replaceIndex); } replaceCompareCharacter += currentCharacter; } return output; }

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

newString现在是'Thas as a strange '

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

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

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

var pattern = "foobar",
    re = new RegExp(pattern, "g");
// Find, Replace, Case
// i.e "Test to see if this works? (Yes|No)".replaceAll('(Yes|No)', 'Yes!');
// i.e.2 "Test to see if this works? (Yes|No)".replaceAll('(yes|no)', 'Yes!', true);
String.prototype.replaceAll = function(_f, _r, _c){ 

  var o = this.toString();
  var r = '';
  var s = o;
  var b = 0;
  var e = -1;
  if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }

  while((e=s.indexOf(_f)) > -1)
  {
    r += o.substring(b, b+e) + _r;
    s = s.substring(e+_f.length, s.length);
    b += e+_f.length;
  }

  // Add Leftover
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }

  // Return New String
  return r;
};

你可以使用以下方法:

newStr = str.replace(/[^a-z0-9]/gi, '_');

or

newStr = str.replace(/[^a-zA-Z0-9]/g, '_');

这将替换所有不是字母或数字的字符('_')。简单地更改下划线值的任何你想替换它。