Symbol.matchAll

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

Symbol.matchAll 靜態資料屬性代表 知名符號 Symbol.matchAllString.prototype.matchAll() 方法會在其第一個引數上查詢此符號,以獲取返回迭代器的函式,該迭代器會生成當前物件與字串的匹配項。

有關更多資訊,請參閱 RegExp.prototype[Symbol.matchAll]()String.prototype.matchAll()

試一試

const re = /\d+/g;
const str = "2016-01-02|2019-03-07";
const result = re[Symbol.matchAll](str);

console.log(Array.from(result, (x) => x[0]));
// Expected output: Array ["2016", "01", "02", "2019", "03", "07"]

知名符號 Symbol.matchAll

Symbol.matchAll 的屬性特性
可寫
可列舉
可配置

示例

使用 Symbol.matchAll

js
const str = "2016-01-02|2019-03-07";

const numbers = {
  *[Symbol.matchAll](str) {
    for (const n of str.matchAll(/\d+/g)) yield n[0];
  },
};

console.log(Array.from(str.matchAll(numbers)));
// ["2016", "01", "02", "2019", "03", "07"]

規範

規範
ECMAScript® 2026 語言規範
# sec-symbol.matchall

瀏覽器相容性

另見