替换字符串中字符的所有实例的最快方法 [英] Fastest method to replace all instances of a character in a string
本文介绍了替换字符串中字符的所有实例的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JavaScript 中替换字符串中所有字符串/字符实例的最快方法是什么?一个 while
,一个 for
循环,一个正则表达式?
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?
推荐答案
最简单的方法是使用带有 g
标志的正则表达式来替换所有实例:
The easiest would be to use a regular expression with g
flag to replace all instances:
str.replace(/foo/g, "bar")
这会将字符串 str
中所有出现的 foo
替换为 bar
.如果您只有一个字符串,您可以将其转换为 RegExp 对象,如下所示:
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");
这篇关于替换字符串中字符的所有实例的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文