Javascript 替换字符串中字符的所有实例的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2116558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest method to replace all instances of a character in a string
提问by Anri?tte Myburgh
What is the fastest way to replace all instances of a string/character in a string in JavaScript? A while, a for-loop, a regular expression?
在 JavaScript 中替换字符串中字符串/字符的所有实例的最快方法是什么?一个while,一个for循环,一个正则表达式?
回答by Gumbo
The easiest would be to use a regular expression with gflag to replace all instances:
最简单的方法是使用带有g标志的正则表达式来替换所有实例:
str.replace(/foo/g, "bar")
This will replace all occurrences of foowith barin the string str. If you just have a string, you can convert it to a RegExp object like this:
这将替换字符串中所有出现的foowith 。如果您只有一个字符串,则可以将其转换为 RegExp 对象,如下所示:barstr
var pattern = "foobar",
re = new RegExp(pattern, "g");
回答by qwerty
Try this replaceAll: http://dumpsite.com/forum/index.php?topic=4.msg8#msg8
试试这个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);
}
It is very fast, and it will work for ALL these conditions that many others fail on:
它非常快,并且适用于许多其他人无法满足的所有这些条件:
"x".replaceAll("x", "xyz");
// xyz
"x".replaceAll("", "xyz");
// xyzxxyz
"aA".replaceAll("a", "b", true);
// bb
"Hello???".replaceAll("?", "!");
// Hello!!!
Let me know if you can break it, or you have something better, but make sure it can pass these 4 tests.
让我知道你是否可以打破它,或者你有更好的东西,但要确保它可以通过这 4 项测试。
回答by Sani Singh Huttunen
var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");
newString now is 'Thas as a strang'
newString 现在是 'Thas as a strang'
回答by Vlada
Also you can try:
您也可以尝试:
string.split('foo').join('bar');
回答by ssamuel68
You can use the following:
您可以使用以下内容:
newStr = str.replace(/[^a-z0-9]/gi, '_');
or
或者
newStr = str.replace(/[^a-zA-Z0-9]/g, '_');
This is going to replace all the character that are not letter or numbers to ('_'). Simple change the underscore value for whatever you want to replace it.
这会将所有不是字母或数字的字符替换为 ('_')。简单地更改下划线值以替换您想要替换的值。
回答by ADamienS
Just thinking about it from a speed issue I believe the case sensitive example provided in the link above would be by far the fastest solution.
仅从速度问题考虑它,我相信上面链接中提供的区分大小写的示例将是迄今为止最快的解决方案。
var token = "\r\n";
var newToken = " ";
var oldStr = "This is a test\r\nof the emergency broadcasting\r\nsystem.";
newStr = oldStr.split(token).join(newToken);
newStr would be "This is a test of the emergency broadcast system."
newStr 将是“这是对紧急广播系统的测试”。
回答by Rick Velde
I think the real answer is that it completely depends on what your inputs look like. I created a JsFiddleto try a bunch of these and a couple of my own against various inputs. No matter how I look at the results, I see no clear winner.
我认为真正的答案是它完全取决于您输入的内容。我创建了一个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; }
- RegExp 在任何测试用例中都不是最快的,但也不错。
- 对于稀疏替换,拆分/加入方法似乎最快。
我写的这个对于小输入和密集替换似乎最快:
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; }
回答by Neel Kamal
Use Regex object like this
像这样使用 Regex 对象
var regex = new RegExp('"', 'g');
str = str.replace(regex, '\'');
var regex = new RegExp('"', 'g');
str = str.replace(regex, '\'');
It will replace all occurrence of "into '.
它将替换所有出现的"into '。
回答by Crozin
What's the fastest I don't know, but I know what's the most readable - that what's shortest and simplest. Even if it's a little bit slower than other solution it's worth to use.
我不知道什么是最快的,但我知道什么是最易读的——最短和最简单的。即使它比其他解决方案慢一点,也值得使用。
So use:
所以使用:
"string".replace("a", "b");
"string".replace(/abc?/g, "def");
And enjoy good code instead of faster (well... 1/100000 sec. is not a difference) and ugly one. ;)
并享受好的代码而不是更快(嗯...... 1/100000 秒。没有区别)和丑陋的代码。;)
回答by Frank W. Zammetti
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...
在意识到我可能接近 10 年前写的一个实现实际上并没有完全工作之后,我尝试了许多这些建议(一个被遗忘已久的系统中令人讨厌的生产错误,这不是总是这样吗?!) ...我注意到的是,我尝试过的那些(我没有全部都尝试过)与我的有同样的问题,也就是说,它们不会替换每一次出现,只有第一个,至少对于我的测试用例通过将“..”替换为“.”,将“test....txt”降为“test.txt”......也许我错过了正则表达式的情况?但我离题了...
So, I rewrote my implementation as follows. It's pretty darned simple, although I suspect not the fastest but I also don't think the difference will matter with modern JS engines, unless you're doing this inside a tight loop of course, but that's always the case for anything...
所以,我重写了我的实现如下。这非常简单,虽然我怀疑不是最快的,但我也不认为现代 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;
}
Hope that helps someone!
希望对某人有所帮助!

