In this tutorial, I’ll go over the replaceAll method, which adds 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 the above string with test with java word with javascript?

string replace method which replaces only the first occurrence of a substring

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

And the output is

This is a java program that contains test code;

Then, how do you replace all matching substrings?

You can use regular expression

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

It will replace all matching strings.

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

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

String.prototype.replaceAll method

replaceAll method is used to replace matched substring with new strings

Here is a syntax.

String.prototype.replaceAll(searchString, replaceString)

Arguments: searchString - input string that needs replace. it can be a string or a regular expression replaceString - input string replace arg1 with this.

Return:

This method returns a new string after replacing the substring with a 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 the same as replace method if searchString is a regular expression.

Here is a 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 the same for both methods when the first argument is a regular expression.