ES2021 - ReplaceAll method

This tutorial covers latest javascript features, String prototype ReplaceAll method in ES12 or ES2021 or EcmaScript2021 ..

In this tutorial, I’ll go over the replaceAll method, which was added to the String object in the most recent version of JavaScript.

Before EcmaScript2021,

Let’s have a given string

String input="This is a test program which contains test code";

How do you replace replace the above string with test with java word with javascript?

string replace method which replaces only first occurrence of a sub string

input = input.replace('test', 'java');

And the output is

This is a java program which contains test code;

Then, how do you replace all matching substrings?

You can use regular expression

input = input.replace(/test/g, 'java');

This will replace all matching strings.

Regular expressions are unsafe to use because they contain escape characters that are needed for certain functions and these are not readable.

To prevent such issues, the latest version of javascript includes a built-in replaceAll method.

String.prototype.replaceAll method

replaceAll method is used to replace matched substring with new strings

Here is an syntax

String.prototype.replaceAll(searchString, replaceString)

Arguments: searchString - input string which need replace. it can be string or regular expression replaceString - input string replace arg1 with this.

Return:

This method returns new string after replacing substring with new string of a given input string.

Here is an example:

'w3schools.website'.replaceAll('website', 'io');

And output

w3schools.io

Please note replaceAll method works same as replace method if searchString is a regular expression.

Here is an replaceAll regular expression example code

String inputString="es2021 first sample code first";
console.log(inputString.replaceAll(/first/g, ''));
console.log(inputString.replace(/first/g, ''));

Output

es2021 sample code first
es2021 sample code first

The output is same for both of this methods when first argument is regular expression.