JavaScript String 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 中引入。
replaceAll()
方法在 Internet Explorer 中无法使用。
语法
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();
});
自己动手试一试 »