JavaScript String replaceAll()

Definition and usage

replaceAll() The method is used to search for a specified value or regular expression in a string.

replaceAll() The method returns a new string with all the matched values replaced.

replaceAll() The method does not change the original string.

replaceAll() The method was introduced in JavaScript 2021.

replaceAll() The method is not available in Internet Explorer.

Note

If the parameter is a regular expression, the global flag must be set (g),否则会抛出 TypeError。

For more information about regular expressions, please see:

Regular expression tutorial

Regular expression reference

Instance

Example 1

text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");

Try it yourself

Example 2

text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");

Try it yourself

Example 2

Global, case-insensitive replacement:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replaceAll(/blue/gi, "red");

Try it yourself

Example 3

Use the function to return the replaced text:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replaceAll(/blue|house|car/gi, function (x) {
  return x.toUpperCase();
});

Try it yourself

Syntax

string.replaceAll(searchValue, newValue)

Parameters

Parameters Description
searchValue Required. The value or regular expression to be searched for.
newValue Required. The new value to be replaced. It can be a JavaScript function.

Return value

Type Description
String Retourne une nouvelle chaîne où toutes les valeurs correspondantes ont été remplacées.