日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2025/3/15 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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()的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。