transformation
String.prototype.replaceAll
Returns a new string with every occurrence of pattern replaced. Added in ES2021; if pattern is a RegExp it must have the g flag or replaceAll throws TypeError.
str.replaceAll(pattern, replacement) Parameters
| Parameter | Purpose |
|---|---|
| pattern | String or global RegExp to match |
| replacement | Replacement string or function called for each match |
Examples
console.log('foo foo foo'.replaceAll('foo', 'bar')); Prints 'bar bar bar'
console.log('a1 b2 c3'.replaceAll(/\d/g, '#')); Prints 'a# b# c#'
console.log('hello'.replaceAll('', '-')); Prints '-h-e-l-l-o-'
console.log('abc'.replaceAll('b', m => m.toUpperCase())); Prints 'aBc'
Gotcha
Non-global RegExp throws TypeError — use /g or a plain string. ES2021 feature; unavailable in older environments (Node < 15, IE).
Related methods
String.prototype.replace
Returns a new string with the first match of pattern replaced. Pattern can be a string (only the first occurrence) or a RegExp (all occurrences when the g flag is set).
String.prototype.matchAll
Returns an iterator of all detailed match results, each including capture groups, index, and input. Added in ES2020 and requires a global (g) RegExp — non-global patterns throw TypeError.
String.prototype.split
Divides the string into an array of substrings using separator (string or RegExp). With no separator the whole string is returned as a one-element array; with '' each UTF-16 code unit becomes an element.
String.prototype.toUpperCase
Returns a new string with all characters converted to upper case using the Unicode default case mapping. Locale-insensitive — use toLocaleUpperCase for language-specific rules (e.g. Turkish i).
String.prototype.toLowerCase
Returns a new string with all characters converted to lower case using Unicode default case mapping. For locale-specific behavior use toLocaleLowerCase.