ES2020 - String.prototype.replaceAll

In JavaScript when we need to replace a substring occurrence in a string we use replace
method:
The tricky part is that replace
method replaces only the very first match of the substring we have passed:
In order to go through this, we need to use a global regexp instead:
So replaceAll
is going to make this a lot easier to us when passing just a string occurrence:
The benefit here might seem really small at first. If we think a little more though, the fact that we are forced to use regular expressions during runtime sometimes might become a little tricky.
Let's say we have a string like my/nested/path
and we need to replace /
with a -
in order to provide a SEO friendly slug. How can we do this?
We need replace
with a global regexp:
Oops, this won't work obviously. We need to escape /
in the regular expression like so \/
to make it work:
Let's do the same by using replaceAll
:
Much easier right? ๐
So we had to be proactive and escape the /
in order to help replace
to do its job. If we haven't done so, our code would fail awfully as we saw.
What if we have a generic function that does some string replacement during runtime and, we don't know exactly what are the substrings we are looking for upfront? Would it be possible to end up with some unwanted exceptions?
Sure!! We need to be super-cautious and know exactly what we have to escape, right?
So this is the main problem that replaceAll
solves, by making such replacements easy during runtime without the need of error-prone regular expressions since it accepts simple string arguments. Cheers!!
At the moment of this writing, String.prototype.replaceAll is in stage 3 of the process which is considered candidate
We can use it with the help of core-js
Did you like this one?
I hope you really did...
Newsletter
Get notified about latest posts and updates once a week!!
You liked it?