📘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:
(unlike the other pattern-matching methods) matchAll() never modifies the lastIndex of the RegExp, and this makes it much less likely to cause bugs.
str.matchAll() returns an iterable iterator.
JS.info ⟩ matchAll() with groups
String.prototype.matchAll()
RegExp: lastIndex - the index at which to start the next match.
Last updated