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

浏览器兼容性

另见