实现说明
演示用的数据放在这几个模块级绑定中: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);