TypeError: matchAll/replaceAll must be called with a global RegExp
當使用 String.prototype.matchAll() 或 String.prototype.replaceAll() 方法時,如果使用的 RegExp 物件未設定 global 標誌,則會丟擲 JavaScript 異常 "TypeError: matchAll/replaceAll must be called with a global RegExp"。
訊息
TypeError: String.prototype.matchAll called with a non-global RegExp argument (V8-based) TypeError: String.prototype.replaceAll called with a non-global RegExp argument (V8-based) TypeError: matchAll must be called with a global RegExp (Firefox) TypeError: replaceAll must be called with a global RegExp (Firefox) TypeError: String.prototype.matchAll argument must not be a non-global regular expression (Safari) TypeError: String.prototype.replaceAll argument must not be a non-global regular expression (Safari)
錯誤型別
TypeError
哪裡出錯了?
String.prototype.matchAll() 和 String.prototype.replaceAll() 方法要求 RegExp 物件設定 global 標誌。此標誌表示正則表示式可以匹配輸入字串的所有位置,而不是在第一次匹配時停止。儘管在使用這些方法時 g 標誌是多餘的(因為這些方法總是執行全域性替換),但仍需要它們來明確意圖。
值得注意的是,g 標誌驗證是在 matchAll 和 replaceAll 方法中完成的。如果你改用 RegExp 的 [Symbol.matchAll]() 方法,則不會出現此錯誤,但只會有一個匹配項。
示例
無效案例
js
"abc".matchAll(/./); // TypeError
"abc".replaceAll(/./, "f"); // TypeError
有效情況
如果你打算進行全域性匹配/替換:請新增 g 標誌,或者如果想保持原始正則表示式不變,則使用 g 標誌構造一個新的 RegExp 物件。
js
[..."abc".matchAll(/./g)]; // [[ "a" ], [ "b" ], [ "c" ]]
"abc".replaceAll(/./g, "f"); // "fff"
const existingPattern = /./;
const newPattern = new RegExp(
existingPattern.source,
`${existingPattern.flags}g`,
);
"abc".replaceAll(newPattern, "f"); // "fff"
如果你只打算進行單個匹配/替換:請改用 String.prototype.match() 或 String.prototype.replace()。如果你想要一個類似 matchAll 返回的迭代器,且只包含一個匹配項,也可以使用 [Symbol.matchAll]() 方法,但這會非常令人困惑。
js
"abc".match(/./); // [ "a" ]
"abc".replace(/./, "f"); // "fbc"
[..././[Symbol.matchAll]("abc")]; // [[ "a" ]]