← 中文资源

简体中文版本

matchAll 必须带 g 标志

matchAll 遇到非全局正则直接抛 TypeError(否则第一个位置会无限匹配);它内部克隆正则做迭代,原正则的 lastIndex 保持 0,而 exec 循环会推进 lastIndex 需要手动复位。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

without /g: TypeError
with /g: 1,2,3
original lastIndex after matchAll: 0

实现说明

演示用的数据放在这几个模块级绑定中:pattern、found。

使用要点

  • 演示输出是带标签的(without /g:、with /g:、original lastIndex after matchAll:),每个操作都会留下自己的一行标注。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 状态都挂在模块顶层:pattern、found。

核心语句

const found = [...'a1b2c3'.matchAll(pattern)];
'a1b2'.matchAll(/\d/);
const pattern = /\d/g;

代码示例

// matchAll requires the /g flag: a non-global regex would match the first
// position forever, so the engine refuses up front with a TypeError.
try {
  'a1b2'.matchAll(/\d/);
} catch (error) {
  console.log('without /g:', error.constructor.name);
}

const pattern = /\d/g;
const found = [...'a1b2c3'.matchAll(pattern)];
console.log('with /g:', found.map((m) => m[0]).join(','));

// matchAll iterates a clone: the original regex lastIndex stays 0, while
// an exec loop advances it and must be reset between inputs.
console.log('original lastIndex after matchAll:', pattern.lastIndex);