UPDATE June 2020: This feature has advanced to Stage-4 and will be part of the ES2021 Specification! π
An ECMAScript Language feature that’s currently in Stage-3 is String.prototype.replaceAll
, a handy way to replace all instances of a piece of text in a string.
πββοΈ Stage-3?
The Technical Committee which is concerned with the standardization of ECMAScript (i.e. TC39) has a 5 stage process in place, ranging from stage-0 to stage-4, by which it develops a new language feature.
Stage-3 is the Candidate Stage where the feature is considered complete and only critical changes will happen based on implementation experience. If all goes well the proposal will advance to Stage 4 without any changes, after which it will to become part of the ECMAScript Specification.
~
The Problem
If you ever needed to replace a piece of text in a string you most likely will have used String.prototype.replace
:
'the quick brown fox jumps over the lazy dog'.replace('a', '_')
// ~> "the quick brown fox jumps over the l_zy dog"
There’s one somewhat counterintuitive issue with it though: it only replaces the first match it finds:
'the quick brown fox jumps over the lazy dog'.replace('o', '_')
// ~> "the quick br_wn fox jumps over the lazy dog"
One of the workarounds we can use today is to use a global regular expression (e.g. a RegEx with the g
flag):
'the quick brown fox jumps over the lazy dog'.replace(/o/g, '_')
// ~> "the quick br_wn f_x jumps _ver the lazy d_g"
~
The Solution
The String.prototype.replaceAll
proposal offers us a non-hacky solution, right in the JavaScript language:
'the quick brown fox jumps over the lazy dog'.replaceAll('o', '_')
// ~> "the quick br_wn f_x jumps _ver the lazy d_g"
Its method signature is exactly the same as String.prototype.replace
‘s:
String.prototype.replaceAll(searchValue, replaceValue)
Implementation-wise it differs in only two ways from String.prototype.replace
:
- When given a string as its
searchValue
:replaceAll
will replace all occurrences, whereasreplace
will only replace the first β hence why it is being proposed in the first place. - When given a non-global regular expression (e.g. a RegEx without the
g
flag) as itssearchValue
:replaceAll
will throw an exception as the wordreplaceAll
implies to “replace all” but the lack of theg
flag implies exactly the opposite β Computer says no.
~
Browser Support
Although the feature is Stage-3 already, it’s not enabled in browsers yet. To test this feature:
- In Chrome: Enable
#enable-javascript-harmony
inchrome://flags/
- In Firefox: N/A
- In Safari: Enabled in Safari Technology Preview Release 97
~
Thank me with a coffee.
I don\'t do this for profit but a small one-time donation would surely put a smile on my face. Thanks!
To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.