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


当前回答

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

newString现在是'Thas as a strange '

其他回答

我认为真正的答案是,这完全取决于你的输入是什么样的。我创建了一个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 regex = new RegExp(' ' ', 'g'); STR = STR .replace(regex, '\ ");

它将取代所有出现的“into”。

你可以使用以下方法:

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

or

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

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

你也可以试试:

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

试试这个replaceAll: http://dumpsite.com/forum/index.php?topic=4.msg8#msg8

String.prototype.replaceAll = function(str1, str2, ignore) 
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} 

这是非常快的,它将工作在所有这些条件 很多人都没有做到的:

"x".replaceAll("x", "xyz");
// xyz

"x".replaceAll("", "xyz");
// xyzxxyz

"aA".replaceAll("a", "b", true);
// bb

"Hello???".replaceAll("?", "!");
// Hello!!!

让我知道你是否可以打破它,或者你有更好的东西,但要确保它能通过这4个测试。