Consider a case, where you want to replace all occurrences of a user provided string with something else, maybe an empty string. Since we don't have something like RegExp.escape (yet), it's quite difficult to do it right in vanilla JS.
But with replaceAll, you just do text.replaceAll(externalString, '') and you're done.
This new method can also have positive effects in terms of performance, since no regular expression had to be parsed and executed for this relatively simple task.
Although there is also another way, which is available today, but it may not be obvious for everyone.
It is the split/join technique: text.split(replaceThat).join(withThat)
Can't one be done with regex /g tag with normal replace function.
It's like
.sub
and.gsub
methods in the Ruby.Consider a case, where you want to replace all occurrences of a user provided string with something else, maybe an empty string. Since we don't have something like RegExp.escape (yet), it's quite difficult to do it right in vanilla JS.
But with replaceAll, you just do
text.replaceAll(externalString, '')
and you're done.This new method can also have positive effects in terms of performance, since no regular expression had to be parsed and executed for this relatively simple task.
Although there is also another way, which is available today, but it may not be obvious for everyone.
It is the split/join technique:
text.split(replaceThat).join(withThat)
That's probably what's happening under the hood. This new method is just a way to make it easier