JavaScript 字符串 replaceAll() 方法
示例
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");亲自试一试 »
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");亲自试一试 »
以下是更多示例。
描述
replaceAll() 方法会在字符串中查找指定的值或正则表达式。
replaceAll() 方法会返回一个所有值都被替换的新字符串。
replaceAll() 方法不会更改原始字符串。
replaceAll() 方法在 JavaScript 2021 版本中引入。
语法
string.replaceAll(searchValue, newValue)
参数
| 参数 | 描述 |
| searchValue | 必填项。 要搜索的值或正则表达式。 |
| newValue | 必填。 新值(要替换为)。 此参数可以是 JavaScript 函数。 |
返回值
| 类型 | 描述 |
| 一个字符串 | 一个新字符串,其中搜索值已被替换。 |
更多示例
一个全局的、不区分大小写的替换:
let text = "Mr Blue has a blue house and a blue car";
let result = text.replaceAll(/blue/gi, "red");亲自试一试 »
返回替换文本的函数:
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();
});亲自试一试 »