โจquick brown fox
JS โฉ value โฉ object โฉ regex โฉ example โฉ quick brown fox
use matchAll() with /d
, /g
, /i
flags.
replit โฉ quick brown fox
// โญ custom pattern
// ------------------
// โข match "quick brown" followed by "jumps", ignoring characters in between.
// โข remember "brown" and "jumps" (groups)
// โข flags:
// โข /i - ignore case
// โข /g - global search
// โข /d - generate indices โญ
// โญโโโโ G1 โโโโโโฎ โญโG2โโโฎ
const regex = /quick\s(?<color>brown).+?(jumps)/dgi;
// โฐโโฏ any 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
// โญ๏ธ pattern matching without generating indices
const regexWithoutGeneratingIndices = /quick\s(?<color>brown).+?(jumps)/gi;
const matches2 = [...str.matchAll(regexWithoutGeneratingIndices)];
;[
// โญ๏ธ with indices
matches[0], // first match
// [
// 'Quick Brown Fox Jumps', // the "match" (substring)
// 'Brown', // capture group #1
// 'Jumps', // capture group #2
//
// index: 4, // index for the "match"
// input: 'The Quick Brown ...', // original string
// groups: { color: 'Brown' }, // named groups
//
// indices: [ // indices for match/groups โญ๏ธ
// [ 4, 25 ],
// [ 10, 15 ],
// [ 20, 25 ],
// groups: { color: [ 10, 15 ] } // indices for named groups
// ]
// ]
matches[0][0], // the "match": 'Quick Brown Fox Jumps'
matches[0].groups, // named groups: { color: 'Brown' }
matches[0].indices, // indices for match/groups: [[4,25], [10,15], [20,25]]
matches[0].indices.groups, // indices for named groups: { color: [ 10, 15 ] }
// โญ๏ธ without generating indices
matches2[0], // first match
// [
// 'Quick Brown Fox Jumps',
// 'Brown',
// 'Jumps',
//
// index: 4,
// input: 'The Quick Brown Fox Jumps Over The Lazy Dog',
// groups: { color: 'Brown' }
// ]
].forEach(x => console.log(x));
Last updated