【ES11(2020)】String 扩展 String.prototype.matchAll()

matchAll()方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// ["test1", "e", "st1", "1"]

console.log(array[1]);
// ["test2", "e", "st2", "2"]

语法:str.matchAll(regexp)

matchAll出现之前,通过在循环中调用regexp.exec()来获取所有匹配项信息(regexp 需使用 /g 标志):

const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
let match;

while ((match = regexp.exec(str)) !== null) {
  console.log(`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`);
  // expected output: "Found football start=6 end=14."
  // expected output: "Found foosball start=16 end=24."
}

如果使用matchAll,就可以不必使用 while循环加exec方式(且正则表达式需使用/g标志)。使用 matchAll会得到一个迭代器的返回值,配合for...of, array spread, 或者 Array.from() 可以更方便实现功能:

const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
const matches = str.matchAll(regexp);

for (const match of matches) {
  console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
}

Array.from(str.matchAll(regexp), m => m[0]);
// Array [ "football", "foosball" ]

如果没有/g标志,matchAll会抛出异常。

matchAll 内部做了一个 regexp 的复制,所以不像 regexp.exec, lastIndex在字符串扫描时不会改变。

const regexp = RegExp('[a-c]','g');
regexp.lastIndex = 1;
const str = 'abc';
Array.from(str.matchAll(regexp), m => `${regexp.lastIndex} ${m[0]}`);
// [ "1 b", "1 c" ]
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优小U

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值