ESNext: Replace all occurrences of a piece of text in a string with String.prototype.replaceAll

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?

💁‍♂️ 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.

~

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:

  1. When given a string as its searchValue: replaceAll will replace all occurrences, whereas replace will only replace the first — hence why it is being proposed in the first place.
  2. When given a non-global regular expression (e.g. a RegEx without the g flag) as its searchValue: replaceAll will throw an exception as the word replaceAll implies to “replace all” but the lack of the g 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 in chrome://flags/
  • In Firefox: N/A
  • In Safari: Enabled in Safari Technology Preview Release 97

~

Did this help you out? Like what you see?
Consider donating.

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!

☕️ Buy me a Coffee ($3)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.