Skip to content
Related Articles

Related Articles

Improve Article

JavaScript String replaceAll() Method

  • Last Updated : 22 Jan, 2021

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!



My Personal Notes arrow_drop_up
Recommended Articles
Page :