Replace Every Match with JavaScript `String.replaceAll()`
1
min read .
Updated on
String.prototype.replaceAll() replaces every occurrence of a substring or every match of a global regular expression and returns a new string.
Replace a Literal Substring
const text = 'Hello World! Welcome to the World of JavaScript.';
const result = text.replaceAll('World', 'Universe');Use a Regular Expression
When searchValue is a RegExp, it must use the g flag:
const text = 'The rain in Spain stays mainly in the plain.';
const result = text.replaceAll(/ain/g, 'oon');Dynamic Replacement Function
const fruits = 'apple, banana, cherry';
const upper = fruits.replaceAll(/\b\w+/g, (word) => word.toUpperCase());
console.log(upper); // APPLE, BANANA, CHERRY
Do Not Treat Replacement as HTML Sanitization
Removing a few special characters with replaceAll() is not a reliable defense against cross-site scripting or other injection attacks. Use context-appropriate escaping or a proven sanitizer when inserting untrusted HTML.
Conclusion
Use replaceAll() when the intent is to replace every occurrence and you want that behavior to be explicit. It works with literal strings, global regular expressions, and replacement callbacks while leaving the original string unchanged.