Thursday, September 4, 2025
HomeLanguagesJavascriptJavaScript String replaceAll() Method

JavaScript String replaceAll() Method

The Javascript 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 substrings which are to replace with newSubstr or the value returned by the specified function.
  • newSubstr: It is the substring 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: Below is an example of the String replaceAll() Method.

Javascript




function gfg() {
    let string = "Geeks or Geeks";
    newString = string.replaceAll("or", "for");
    console.log(newString);
}
gfg();


Output:

Geeks for Geeks

More examples of the replaceAll() method are given below:

Example 1: In this example, we will replace all occurrences of the Hello word with Hi using the replaceAll() method in Javascript.

Javascript




function GFG() {
    let string = "Hello, what are you doing?";
    newString = string.replaceAll("Hello", "Hi");
    console.log(newString);
}
GFG();


 Output :

Hi, what are you doing?

Example 2: In this example, we will replace all occurrences of the coffee world with tea using the replaceAll() method in Javascript.

Javascript




function GFG() {
    const regexp = /coffee/ig;
    let string = "Lets, have coffee today!";
    newString = string.replaceAll(regexp, "tea");
    console.log(newString);
}
GFG();


 Output:

Lets, have tea today!

We have a complete list of Javascript string methods, to check those please go through the Javascript String Complete Reference article.

Supported Browser:

  • Chrome 85 and above
  • Edge 85 and above
  • Firefox 77 and above
  • Opera 71 and above
  • Safari 13.1 and above
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS