JavaScript String replaceAll() Method
Below is an example of the String replaceAll() Method.
Javascript
<script> function gfg() { let string = "Geeks or Geeks" ; newString = string.replaceAll( "or" , "for" ); document.write(newString); } gfg(); </script> |
Output:
Geeks for Geeks
The replaceAll() method returns a new string after replacing all the matches of a string with a specified string or a regular expression.
The original string is left unchanged after this operation.
Syntax:
const newString = originalString.replaceAll(regexp | substr , newSubstr | function)
Parameters: This method accepts certain parameters defined below:
- regexp: It is the regular expression whose matches are replaced with the newSubstr or the value returned by the specified function.
- substr: It defines the sub strings which are to replace with newSubstr or the value returned by the specified function.
- newSubstr: It is the sub string that replaces all the matches of the string specified by the substr or the regular expression.
- function: It is the function that is invoked to replace the matches with the regexp or substr.
Example 1:
Javascript
<script> function GFG() { let string = "Hello, what are you doing?" ; newString = string.replaceAll( "Hello" , "Hi" ); document.write(newString); } GFG(); </script> |
Output :
Hi, what are you doing?
Example 2:
Javascript
<script> function GFG() { const regexp = /coffee/ig; let string = "Lets, have coffee today!" ; newString = string.replaceAll(regexp, "tea" ); document.write(newString); } GFG(); </script> |
Output:
Lets, have tea today!
Supported Browser:
- Chrome 85 and above
- Edge 85 and above
- Firefox 77 and above
- Opera 71 and above
- Safari 13.1 and above