String.prototype.replaceAll()
replaceAll() 方法用於 String 值,它會返回一個新的字串,其中所有匹配 pattern 的部分都被 replacement 替換。pattern 可以是字串或 RegExp,而 replacement 可以是字串或一個為每個匹配項呼叫的函式。原始字串將保持不變。
試一試
const paragraph = "I think Ruth's dog is cuter than your dog!";
console.log(paragraph.replaceAll("dog", "monkey"));
// Expected output: "I think Ruth's monkey is cuter than your monkey!"
// Global flag required when calling replaceAll with regex
const regex = /dog/gi;
console.log(paragraph.replaceAll(regex, "ferret"));
// Expected output: "I think Ruth's ferret is cuter than your ferret!"
語法
replaceAll(pattern, replacement)
引數
pattern-
可以是字串或具有
Symbol.replace方法的物件 — 最常見的例子是 正則表示式。任何不具有Symbol.replace方法的值都將被強制轉換為字串。 replacement-
可以是字串或函式。替換的語義與
String.prototype.replace()的語義相同。
返回值
一個新的字串,其中所有匹配模式的部分都已替換為指定的替換項。
異常
描述
此方法不會修改其呼叫的字串值。它會返回一個新字串。
與 replace() 不同,此方法會替換字串中的所有出現項,而不僅僅是第一個。雖然也可以使用動態構建的全域性正則表示式與 RegExp() 來結合使用 replace() 以替換字串中的所有例項,但如果字串包含在正則表示式中有特殊含義的字元(這可能會在替換字串來自使用者輸入時發生),這可能會導致意外的後果。雖然可以使用 RegExp.escape() 來緩解這種情況,將正則表示式字串轉換為字面量模式,但更簡單的方法是直接將字串傳遞給 replaceAll(),而無需將其轉換為正則表示式。
function unsafeRedactName(text, name) {
return text.replace(new RegExp(name, "g"), "[REDACTED]");
}
function semiSafeRedactName(text, name) {
return text.replaceAll(name, "[REDACTED]");
}
function superSafeRedactName(text, name) {
// only match at word boundaries
return text.replaceAll(
new RegExp(`\\b${RegExp.escape(name)}\\b`, "g"),
"[REDACTED]",
);
}
let report =
"A hacker called ha.*er used special characters in their name to breach the system.";
console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system."
console.log(semiSafeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system."
report = "A hacker called acke breached the system.";
console.log(semiSafeRedactName(report, "acke")); // "A h[REDACTED]r called [REDACTED] breached the system."
console.log(superSafeRedactName(report, "acke")); // "A hacker called [REDACTED] breached the system."
如果 pattern 是一個具有 Symbol.replace 方法的物件(包括 RegExp 物件),則該方法將使用目標字串和 replacement 作為引數進行呼叫。其返回值將成為 replaceAll() 的返回值。在這種情況下,replaceAll() 的行為完全由 [Symbol.replace]() 方法編碼,因此將與 replace() 產生相同的結果(除了對正則表示式是否全域性的額外輸入驗證)。
如果 pattern 是一個空字串,則替換項將插入到每個 UTF-16 碼單元之間,這類似於 split() 的行為。
"xxx".replaceAll("", "_"); // "_x_x_x_"
有關正則表示式屬性(特別是 粘性標誌)如何與 replaceAll() 互動的更多資訊,請參閱 RegExp.prototype[Symbol.replace]()。
示例
使用 replaceAll()
"aabbcc".replaceAll("b", ".");
// 'aa..cc'
非全域性正則表示式丟擲錯誤
使用正則表示式作為搜尋值時,它必須是全域性的。這行不通
"aabbcc".replaceAll(/b/, ".");
// TypeError: replaceAll must be called with a global RegExp
這將起作用
"aabbcc".replaceAll(/b/g, ".");
("aa..cc");
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string.prototype.replaceall |
瀏覽器相容性
載入中…