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:
- 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:
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