Replacing All Occurrences of a String in Javascript

The replaceAll() method is used to find all occurrences of the specified substring and replace them with the desired replacement string.

 
let originalString = "The school has many students. The students are learning new things every day.";
let replacedString = originalString.replaceAll("student", "pupil");
 
console.log("Original string:", originalString);
console.log("Replaced string:", replacedString);
//Original string:  The school has many students. The students are learning new things every day.
// Replaced string: The school has many pupils. The pupils are learning new things every day.

Key points:

 

  • Use the replaceAll() method to replace all occurrences of a substring with another string.
  • It's a relatively new method, introduced in ES2021, so ensure browser compatibility if targeting older versions.
  • Pass the substring to be replaced as the first argument, and the replacement string as the second argument.
  • The method returns a new string with the replacements; it doesn't modify the original string.