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.
The Technical Committee which is concerned with the standardization of ECMAScript (e.g. 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.
If you ever needed to replace a piece of text in a string you most likely will have used
'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
'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 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
Implementation-wise it differs in only two ways from
- When given a string as its
replaceAllwill replace all occurrences, whereas
replacewill 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
gflag) as its
replaceAllwill throw an exception as the word
replaceAllimplies to “replace all” but the lack of the
gflag implies exactly the opposite — Computer says no.
Although the feature is Stage-3 already, it’s not enabled in browsers yet. To test this feature:
- In Chrome: Enable
- In Firefox: N/A
- In Safari: Enabled in Safari Technology Preview Release 97