JavaScript String replaceAll()

定义和用法

replaceAll() 方法用于在字符串中搜索指定的值或正则表达式。

replaceAll() 方法返回一个所有匹配值都被替换的新字符串。

replaceAll() 方法不会改变原始字符串。

replaceAll() 方法是在 JavaScript 2021 中引入的。

replaceAll() 方法在 Internet Explorer 中不可用。

注意

如果参数是正则表达式,必须设置全局标志(g),否则会抛出 TypeError。

更多关于正则表达式的内容,请参阅:

正则表达式教程

正则表达式参考

实例

例子 1

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

亲自试一试

例子 2

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

亲自试一试

例子 2

全局、不区分大小写的替换:

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

亲自试一试

例子 3

使用函数返回替换文本:

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();
});

亲自试一试

语法

string.replaceAll(searchValue, newValue)

参数

参数 描述
searchValue 必需。要搜索的值或正则表达式。
newValue 必需。用于替换的新值。可以是 JavaScript 函数。

返回值

类型 描述
String 返回新字符串,其中所有匹配值已被替换。