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


当前回答

像这样使用正则表达式对象

var regex = new RegExp(' ' ', 'g'); STR = STR .replace(regex, '\ ");

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

其他回答

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

所以使用:

 "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");

你也可以试试:

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个测试。

像这样使用正则表达式对象

var regex = new RegExp(' ' ', 'g'); STR = STR .replace(regex, '\ ");

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