【ES11(2020)】String 扩展 String.prototype.matchAll()
生活随笔
收集整理的這篇文章主要介紹了
【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" ]總結
以上是生活随笔為你收集整理的【ES11(2020)】String 扩展 String.prototype.matchAll()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c纳秒级计时器_纳秒级性能计时器
- 下一篇: 数字类 default 0和 defau