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.
💁♂️ To develop new ECMAScript language features, TC39 uses a 5 stage process, ranging from Stage-0 to Stage-4. Stage-3 is the Candidate Stage where the feature is considered complete and only critical changes will happen based on implementation experience.
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
I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!