Let’s have a given string
String input="This is a test program which contains test code";
How do you replace to replace the above string with
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.
replaceAll method to prevent such issues,
replaceAll method is used to replace matched substring with new strings
Here is a syntax
Arguments: searchString - input string that needs replace. it can be a string or a regular expression replaceString - input string replace arg1 with this.
This method returns a new string after replacing the substring with a new string of a given input string.
Here is an example:
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, ''));
es2021 sample code first es2021 sample code first
The output is the same for both methods when the first argument is a regular expression.