Fastest method to replace all instances of a character in a string
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
?
The easiest would be to use a regular expression with g
flag to replace all instances:
str.replace(/foo/g, "bar")
This will replace all occurrences of foo
with bar
in the string str
. If you just have a string, you can convert it to a RegExp object like this:
var pattern = "foobar",
re = new RegExp(pattern, "g");
Try this 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.
var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");
newString现在是'Thas as a strang'
链接地址: http://www.djcxy.com/p/94208.html上一篇: MySQL字符串替换
下一篇: 最快的方法来替换字符串中的所有字符的实例