๐Ÿ“˜str.matchAll()

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๏ผš

Last updated