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
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.
replaceAll method is used to replace matched substring with new strings
Here is an syntax
Arguments: searchString - input string which need replace. it can be string or regular expression replaceString - input string replace arg1 with this.
This method returns new string after replacing substring with new string of a given input string.
Here is an example:
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, ''));
es2021 sample code first es2021 sample code first
The output is same for both of this methods when first argument is regular expression.