๐str.matchAll()
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
JS โฉ primitives โฉ String โฉ methods โฉ .matchAll()
(โญ๏ธ ES2020) returns an iterable iterator of all matching results.
// โข match "quick brown" followed by "jumps", ignoring characters in between.
// โข remember "brown" and "jumps" (groups)
// โข ignore case
// โญโโโโ G1 โโโโโโฎ โญโG2โโโฎ
const regex = /quick\s(?<color>brown).+?(jumps)/dgi;
// โฐโโฏ characters (?: as short as possible, lazy)
// index: |01234567890123456789012345
// | โญโโโโโโ match โโโโโโโฎ
const str = "The Quick Brown Fox Jumps Over The Lazy Dog";
// groups: โฐโ1โโฏ โฐโ2โโฏ
const matches = [...str.matchAll(regex)]; // iterator of matches -> array of matches
// 1. each match is an array โญ๏ธ
// 2. match format:
// โญโโโโโโโ match โโโโโโโโฎ โญโG1โโโฎ โญโG2โโโฎ
// [match, ...groups] = ['Quick Brown Fox Jumps', 'Brown', 'Jumps']
//
// 3. additional properties:
//
// โข index: 4 // index for match
// โข input: "The Quick Brown Fox ... Lazy Dog" // original string
// โข groups: { color: 'Brown' } // named groups
// โข indices: [ [4, 25], [10, 15], [20, 25] ] // indices for match/groups
// โข groups: { color: [10, 15] } // indices for named groups
๐พ ็จๅผ๏ผreplit
// โญ๏ธ pattern: yyyy-mm-dd (โญ๏ธ using "named groups")
// โญ--- year ---โฎ โญ--- month ---โฎ โญ--- day ---โฎ
let date = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
// text
let str = "2019-10-30, 2020-01-01, 18:24:00";
// โญ๏ธโญ๏ธโญ๏ธ result of `str.matchAll()` is an "iterable", NOT an arrayโ๏ธ
let matches = str.matchAll(date);
for (let match of matches) {
let { year, month, day } = match.groups; // โญ๏ธ object destruturing
console.log(`year: ${year}, month: ${month}, day: ${day}`);
}
// output
// -------------------------------
// year: 2019, month: 10, day: 30
// year: 2020, month: 01, day: 01
๐more examples๏ผ