JavaScript (ES2026) reference · String Methods
JavaScript String replaceAll() Method
Replace every occurrence of a string (or regex with the g flag) with new text, without writing a regex.
JavaScript (ES2026) Since ES2021
Syntax
string.replaceAll(pattern, replacement)
Parameters
| Parameter | Description |
|---|---|
pattern |
A string, or a regular expression that has the g flag. |
replacement |
A string or a function. |
Return value
A new string.
Examples
console.log("a-b-c".replaceAll("-", "/"));
Output
a/b/c
try {
"aaa".replaceAll(/a/, "b");
} catch (e) {
console.log(e.constructor.name, "- regex needs the g flag");
}
console.log("aaa".replaceAll(/a/g, "b"));
Output
TypeError - regex needs the g flag bbb
Version history
| Version | Change |
|---|---|
| JavaScript ES2021 | Added |
In other languages
str.replace()· Pythonstr_replace()· PHP
Related
string.replace()· Replace the first match of a string or regex (every match with the g flag) with new text or a function's result.string.split()· Split a string into an array of substrings at each separator (a string or regex), with an optional limit.- JavaScript Strings · tutorial
- JavaScript String Methods · tutorial