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


当前回答

使用String对象的replace()方法。

正如所选答案中提到的,应该在正则表达式中使用/g标志,以便替换字符串中子字符串的所有实例。

其他回答

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

使用String对象的replace()方法。

正如所选答案中提到的,应该在正则表达式中使用/g标志,以便替换字符串中子字符串的所有实例。

@Gumbo添加额外的答案- user.email.replace(/foo/gi,"bar");

/foo/g - Refers to the all string to replace matching the case sensitive

/foo/gi - Refers to the without case sensitive and replace all For Eg: (Foo, foo, FoO, fOO)

DEMO

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

所以使用:

 "string".replace("a", "b");
 "string".replace(/abc?/g, "def");

享受好的代码而不是更快的速度(嗯…1/100000秒不是差)和丑陋的差。;)