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

← All JS string methods · JS array methods