String.prototype.replaceAll
Replaces all occurrences of a substring with another string.
Available since: ES2021
Syntax
str.replaceAll(pattern, replacement)Parameters
| Parameter | Type | Description |
|---|---|---|
| pattern | string | RegExp | What to look for: a string or a regular expression with the `g` flag. |
| replacement | string | Function | The replacement. |
Return value
stringA new string with the replacements applied.
Examples
Replacing every occurrence:
console.log('a-b-c'.replaceAll('-', '+'));Output:
a+b+creplace() with a string replaces only the first occurrence:
console.log('a-b-c'.replace('-', '+'));Output:
a+b-cNotes
The search is case-sensitive. For a case-insensitive replacement, use a regular expression with the gi flags.
See also
- String.prototype.includes — Checks whether a string contains a given substring.
- String.prototype.trim — Removes whitespace from both ends of a string.
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).
- RegExp.escape — Escapes a string so it can be safely put into a regular expression.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.