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 返回新字符串,其中所有匹配值已被替換。