.replaceAll() String Method

I'm back after a short self-imposed break from blogging! Today I want to focus on a new String Method that's getting introduced to JavaScript in ES2021, .replaceAll(). This method returns a new string with all of the matches of a given pattern, replaced by a given replacement.

Consider the following example:

const str = "Joey is hungry for pizza and pizza is hungry for cheese.";
console.log(str.replaceAll("pizza", "spaghetti"));
// Expected result: "Joey is hungry for spaghetti and spaghetti is hungry for cheese."

The Old Way

This is an easier and cleaner way of finding all instances of the pattern you want to replace. Before, we would use the .replace() method, but this wouldn't get us all the way there because the .replace() method only replaces the first instance of the matched pattern with the replacement:

const str = "Joey is hungry for pizza and pizza is hungry for cheese.";
console.log(str.replace("pizza", "spaghetti"));
// Expected output: "Joey is hungry for spaghetti and pizza is hungry for cheese."

As a workaround we would change the pattern to a Regular Expression and pass it the global g flag. Here is how this used to be done, using RegExp:

const str = "Joey is hungry for pizza and pizza is hungry for cheese.";
console.log(str.replace(/pizza/g, "spaghetti"));
// Expected output: "Joey is hungry for spaghetti and spaghetti is hungry for cheese."

With the new .replaceAll() method we can omit the RegEx and simply pass a string as the pattern.

From MDN, here is the syntax:

replaceAll(pattern, replacement);

// Using Regular Expression:
replaceAll(regexp, newSubstr);
replaceAll(regexp, replacerFunction);

// Using a string that's a substring of the original string
replaceAll(substr, newSubstr);
replaceAll(substr, replacerFunction);

We can still pass in a Regular Expression as the pattern if needed, and we can also pass a function as the replacement if we need to do something more sophisticated than just changing out one string for another. For example, we might need to convert from one currency to another within a string.

From MDN: The .replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

See more examples and documentation here.