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.
Syntax:
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!"
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."
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."
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.
Get more articles on Java Script
Read more on Shell and Linux related articles
Refer more on python here : Python