Groups and CapturingLesson 2.1
How capturing groups work in regex
capturing group syntax, group index, match array, nested groups, group numbering order
Groups Let You Extract Sub-Matches
Parentheses do two things: they group part of a pattern (so quantifiers apply to the whole group), and they capture the matched text into a numbered slot you can access after the match.
const m = '2024-06-15'.match(/^(\d{4})-(\d{2})-(\d{2})$/);
// m[0] => '2024-06-15' โ full match
// m[1] => '2024' โ group 1
// m[2] => '06' โ group 2
// m[3] => '15' โ group 3
Group Numbering
Groups are numbered left to right by their opening parenthesis. Nested groups count too โ the outer group gets a lower index than the inner group it contains.
const m = 'abc'.match(/(a(b)c)/);
// m[1] => 'abc' โ outer group
// m[2] => 'b' โ inner group
Using Groups With replace()
In replacements, $1, $2, etc. refer back to captured groups. This is how you reformat data without writing a parser.
'2024-06-15'.replace(/^(\d{4})-(\d{2})-(\d{2})$/, '$2/$3/$1')
// => '06/15/2024'
Groups are one of the highest-leverage features in regex. Once you have the groups, the hard work of extraction is done.
