JavaScript String replaceAll()
Examples
text = text.replaceAll("cats","dogs");
text = text.replaceAll(/cats/g,"dogs");
More example below.
Description
ThereplaceAll() method searches a string for a value or a regular expression.
ThereplaceAll() method returns a new string with all values replaced.
ThereplaceAll() method does not change the original string.
ThereplaceAll() method was introduced in JavaScript 2021.
Note
If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is thrown.
Read more about regular expressions in our:
Syntax
Parameters
| Parameter | Description |
| searchValue | Required. The value, or regular expression, to search for. |
| newValue | Required. The new value (to replace with). This parameter can be a JavaScript function. |
Return Value
| Type | Description |
| A string | A new string where the search values has been replaced. |
More Examples
A global, case-insensitive replacement:
let result = text.replaceAll(/blue/gi, "red");
A function to return the replacement text:
let result = text.replaceAll(/blue|house|car/gi, function (x) {
return x.toUpperCase();
});

