While going through string.replace()
in Eloquent JavaSript 3rd Ed, p.154:
console.log("hello".replace(/l/, "X"));
console.log("hello".replace(/l/g, "X"));
This looks reasonable. But the book also stated:
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.
Why would relying on the g
flag not a good choice? I also found that Ruby really does use a different method gsub
vs sub
, and Python uses re.sub
without count to mean all and a count of 1 to mean once.
What is/are the reason(s) using a replaceAll()
is better than using the g
flag?