JavaScript String replaceAll()

Definition and usage

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

replaceAll() This method returns a new string with all matching values replaced.

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

replaceAll() This method was introduced in JavaScript 2021.

replaceAll() This 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 refer to:

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)

Parameter

Parameter 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 Returns a new string with all matched values replaced.