The JavaScript string.replaceAll() method
The replaceAll() method returns a new string with every occurrence of a pattern replaced. "a-b-c".replaceAll("-", "+") gives "a+b+c". It's the readable answer to the classic problem that plain replace() only swaps the first match.
Overview
replaceAll() exists to fix the most common surprise in JavaScript strings: that replace() with a plain string only changes the first match. replaceAll() changes them all, and it says so right in the name, so your intent is obvious to anyone reading the code.
Before it landed, the workaround was a global regex — str.replace(/-/g, "+") — which works but is easy to get wrong and hard to read for non-regex folks. replaceAll("-", "+") is the plain-English version. It returns a new string, like everything else with strings, since the original can't be mutated.
One rule to know: if you do pass a regular expression to replaceAll(), it must have the global (g) flag, or it throws a TypeError. That's a deliberate guard so the name and behavior always agree. For a simple substring swap, just pass strings and you'll never hit it. Support is solid across all current browsers.
Syntax
const result = str.replaceAll(pattern, replacement)
"a-b-c".replaceAll("-", "+") // "a+b+c"
Parameters
The string.replaceAll() method accepts the following parameters.
| Parameter | Description |
|---|---|
pattern |
The substring to replace everywhere, or a global (/.../g) regular expression. A non-global regex throws. |
replacement |
The replacement string (with $1, $& support) or a function returning the replacement. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const messy = 'one two three';
// collapse every double space to a single one
const clean = messy.replaceAll(' ', ' ');
document.getElementById('out').textContent = clean; // one two three
</script>
Best practices
- Use
replaceAll()for the everyday "swap every occurrence" job — it's clearer than a global regex. - If you pass a regex, include the
gflag or it throws aTypeError. - Use the return value; the original string is never changed.
- For one-off first-match swaps, plain replace() is fine.
Frequently asked questions
What is the difference between replace() and replaceAll()?
replaceAll() swaps every match. Use replaceAll() when you mean all of them.How do I replace all occurrences of a substring?
str.replaceAll("old", "new"). It returns a new string with every occurrence replaced.Why does replaceAll() throw a TypeError?
g flag, e.g. /x/g.