The easiest would be to use a regular expression with g
flag to replace all instances:(最简单的方法是使用带有g
标志的正则表达式替换所有实例:)
str.replace(/foo/g, "bar")
This will replace all occurrences of foo
with bar
in the string str
.(这将用字符串str
bar
替换所有出现的foo
。) If you just have a string, you can convert it to a RegExp object like this:(如果只有字符串,可以将其转换为RegExp对象,如下所示:)
var pattern = "foobar",
re = new RegExp(pattern, "g");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…