What is replaceAll() Method in JavaScript ?

In JavaScript, the replaceAll() method is used to replace all occurrences of a specified substring or pattern within a string with another substring or pattern. It returns a new string with all occurrences replaced.

Syntax:

string.replaceAll(searchValue, newValue)

Parameters:

  • string: The original string in which to perform the replacements.
  • searchValue: The substring or regular expression pattern to be replaced.
  • newValue: The string that replaces each occurrence of searchValue.

Example: Here, the replaceAll() method is called on the str string to replace all occurrences of “fox” with “cat”. The resulting string, "The quick brown cat jumps over the lazy dog.", is stored in the variable newStr.

Javascript




const str = "The quick brown fox jumps over the lazy dog.";
const newStr = str.replaceAll("fox", "cat");
 
console.log(newStr); // Output: "The quick brown cat jumps over the lazy dog."


Output

The quick brown cat jumps over the lazy dog.




Contact Us