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();
});
自己動手試一試 »