String.prototype.replaceAll()

Returns a new string with all matches of a pattern replaced.

Since ES2021 Spec ↗

Syntax

str.replaceAll(pattern, replacement)

Parameters

NameTypeRequiredDescription
pattern string | RegExp Yes A substring or a global (g flag) regular expression to match.
replacement string | Function Yes Replacement string or a function returning the replacement for each match.

Returns

string — A new string with every match replaced.

Throws

  • TypeError — a non-global RegExp is supplied.

Examples

console.log('a-b-c'.replaceAll('-', '+'));
Output
a+b+c
console.log('1 2 3'.replaceAll(/\d/g, 'x'));
Output
x x x

Notes

When using a regex it MUST have the global (g) flag or a TypeError is thrown. Replaces every occurrence with a string pattern, unlike `replace`. Does not mutate the original string.

Browser & runtime support

EnvironmentSince version
chrome 85
firefox 77
safari 13.1
edge 85
node 15

See also