String.prototype.replaceAll()
Added in 2021 to close a twenty-year-old papercut. Its real advantage over a /g regex is that the search text needs no escaping — which matters whenever that text is a variable.
Demo
Compare the first case with the same call on the replace page: here both hyphens change. The fourth case is the quiet advantage — 'a.b' is treated as three literal characters, so 'axb' is left alone. Build the same thing as a regex and the dot becomes a wildcard that matches it. The last case is the one genuine oddity: an empty search string matches at every boundary including both ends, so 'aaa' becomes '-a-a-a-'.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| pattern | string | RegExp | yes | A string matches literally, every time, with no regex interpretation. A RegExp is allowed but must carry the g flag. |
| replacement | string | Function | yes | Same rules as replace: $& $1 $$ are special in a string, while a function replacer inserts its return value verbatim. |
Return value
string — A NEW string with every occurrence replaced. The original is unchanged, as always with strings.
Common patterns
const out = text.replaceAll(needle, replacement);
const slug = title.trim().toLowerCase().replaceAll(' ', '-');
const digits = phone.replaceAll('-', '');
Examples
Pitfalls
'aa'.replaceAll(/a/, 'b')
'aa'.replaceAll(/a/g, 'b')
let s = 'a-b'; s.replaceAll('-', '+'); s
let s = 'a-b'; s = s.replaceAll('-', '+'); s
'x'.replaceAll('x', '$&$&')
'x'.replaceAll('x', () => '$&$&')
'aaa'.replaceAll('', '-')
const out = needle ? s.replaceAll(needle, r) : s;
s.replaceAll('-', '+')
s.replace(/-/g, '+')
When to use
- Replacing every occurrence of literal text
- The search text is a variable that may contain regex metacharacters
- Stripping a character out of a string entirely
- Anywhere a /g regex existed only to get global behaviour
- You genuinely want one replacement → replace
- The pattern is a real pattern → replace with a RegExp
- You need the pieces → split
- Targeting runtimes older than 2021 → the /g regex form
Notes
FAQ
No — for literal text it is generally the same or faster, because the engine can use a plain substring search instead of running the regex machinery. Correctness is the better argument anyway: no escaping, no lastIndex state.