在经历string.replace()
时在 Eloquent JavaSript 第三版,第 154 页:
console.log("hello".replace(/l/, "X"));
console.log("hello".replace(/l/g, "X"));
这看起来很合理。但书中还指出:
It would have been sensible if the choice between replacing one match or all matches was made through an additional argument to
replace
or by providing a different method,replaceAll
. But for some unfortunate reason, the choice relies on a property of the regular expression instead.
为什么要依赖 g
标志不是一个好的选择吗?我还发现Ruby确实使用了不同的方法gsub
与 sub
,Python 使用 re.sub
没有计数表示全部,计数为 1 表示一次。
使用 replaceAll()
的原因是什么?比使用 g
更好旗帜?
最佳答案
要替换所有出现的子字符串,您必须使用带有g
标志的正则表达式。如果您要替换的子字符串来自用户输入或其他变量值,这会变得非常困难。虽然您可以使用 new Regexp(input, 'g') 轻松地根据用户输入构造正则表达式,但此处的输入必须是有效的正则表达式,并且正则表达式引擎将解释其中的特殊符号。例如:
new RegExp('[abc', 'g') // poof
因此,如果有一个 str.replaceAll(input, 'X')
来实现此目的,那就太好了。相反,您需要 weird workarounds .
关于javascript - 为什么在 JavaScript 中,如果有一个方法 ReplaceAll() 可能会更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59967315/