Replace a literal token everywhere
Sanitize or normalize repeated text tokens in a string.
JavaScript · Function
String.prototype.replaceAll() returns a new string in which every match of a string or replacement pattern is replaced. It leaves the original string unchanged.
Call replaceAll with a string or replacement pattern and a replacement string or callback. It produces a new string containing the replacements; a regular-expression pattern must be global, otherwise the call throws a TypeError.
replaceAll(pattern, replacement)| Name | Type | Description |
|---|---|---|
pattern | string | RegExp | object | A string, regular expression, or object with a Symbol.replace method to find. |
replacement | string | function | A replacement string or function used for each match. |
A new string with all matches of the pattern replaced by the replacement.
const input = "red, red, blue";
const output = input.replaceAll("red", "green");
console.log(output); // "green, green, blue"Every occurrence of the string pattern is replaced, while the original string remains unchanged.
Sanitize or normalize repeated text tokens in a string.
Apply pattern-based transformations across all matching substrings.
Compute match-specific output using capture information or surrounding text.
replaceAll returns a new string with every match of the pattern replaced. Unlike replace with a string pattern, it does not stop after the first occurrence.
Follow-up: What happens with a non-global RegExp? It throws a TypeError because replaceAll requires the g flag.
The pattern may be a string or an object providing Symbol.replace, commonly a RegExp. The replacement may be a string or a function invoked for each match.
Follow-up: Why can a custom object participate? replaceAll can call that object's Symbol.replace method with the target string and replacement.
The method leaves the original string unchanged and returns the resulting replacement string. A string pattern is converted as needed, while a regular expression must be global.
Follow-up: When is replace preferable? Use replace when only one replacement is intended or when a non-global regular expression is appropriate.
String.prototype.replace()RegExp.prototype[Symbol.replace]()Symbol.replace