Replacing of all occurrences of a specified string or regular expression using JavaScript : replaceAll()

Java Script @

The replaceAll() method, introduced in ECMAScript 2021, allows for the replacement of all occurrences of a specified string or regular expression pattern within a calling string with a replacement string. Unlike the replace() method, which only substitutes the first match when handling string patterns, replaceAll() substitutes all direct matches found.


The syntax for the replaceAll() method is straightforward:

string.replaceAll(pattern, replacement)
  • pattern: A substring or a global RegExp to match. Note that, unlike replace(), the ‘g’ flag is not required for RegExp because replaceAll() inherently operates globally.
  • replacement: The string that replaces the substrings specified by the pattern, or a function to be invoked to create the new substring(s).

It’s crucial to note that the replaceAll() method throws an error if the first argument is a non-global regular expression.

Examples and Execution: Below are concrete examples of replaceAll() in action. These examples can be executed in any modern JavaScript environment, such as browser developer tools, online coding platforms, or Node.js.

Replacing a substring:

let greet = "Hello, World! World!";
let newGreet = greet.replaceAll("World", "Universe");
console.log(newGreet); // Outputs: "Hello, Universe! Universe!"
Using regular expressions:
let statement = "I love apples, apples are healthy.";
let newStatement = statement.replaceAll(/apples/g, "oranges");
console.log(newStatement); // Outputs: "I love oranges, oranges are healthy."
Using a function
let pricing = "$5 per unit, $10 per dozen.";
let newPricing = pricing.replaceAll(/\$\d+/g, (match) => match + ".00");
console.log(newPricing); // Outputs: "$5.00 per unit, $10.00 per dozen."
Example – Sanitizing user input
function sanitizeInput(input) {
  return input.replaceAll("<script>", "");

let userInput = "Hi! <script>console.log('I am a script')</script>";
let safeInput = sanitizeInput(userInput);
console.log(safeInput); // Outputs: "Hi! console.log('I am a script')"

This function, sanitizeInput, demonstrates a practical scenario where replaceAll() is vital for removing potential script tags from a user’s input, preventing script injection attacks.

Author: user