在JavaScript中替换字符串/字符的所有实例的最快方法是什么?while, for循环,正则表达式?
当前回答
像这样使用正则表达式对象
var regex = new RegExp(' ' ', 'g'); STR = STR .replace(regex, '\ ");
它将取代所有出现的“into”。
其他回答
最简单的方法是使用带有g标志的正则表达式来替换所有实例:
str.replace(/foo/g, "bar")
这将把字符串str中出现的所有foo替换为bar。如果你只有一个字符串,你可以像这样将它转换为RegExp对象:
var pattern = "foobar",
re = new RegExp(pattern, "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
像这样使用正则表达式对象
var regex = new RegExp(' ' ', 'g'); STR = STR .replace(regex, '\ ");
它将取代所有出现的“into”。
我不知道最快的是什么,但我知道最易读的是什么——最短最简单的是什么。即使它比其他溶液慢一点,也值得使用。
所以使用:
"string".replace("a", "b");
"string".replace(/abc?/g, "def");
享受好的代码而不是更快的速度(嗯…1/100000秒不是差)和丑陋的差。;)
你也可以试试:
string.split('foo').join('bar');