Nested Capture Groups
You'll learn how nested parentheses create multiple capture groups with numbering determined by their opening positions.
The Core Idea
When you place one set of capturing parentheses inside another, JavaScript creates multiple capture groups. The numbering isn't based on closing order or nesting depth—it's based strictly on the order in which the opening parentheses appear from left to right.
Think of it like reading a book: you number the chapters as you encounter them, not when you finish them.
How Numbering Works
const pattern = /(outer (inner))/;
const text = "outer inner";
const result = pattern.exec(text);
console.log(result[0]); // "outer inner" - full match
console.log(result[1]); // "outer inner" - group 1
console.log(result[2]); // "inner" - group 2
Group 1 is numbered first because its opening ( comes first. Group 2 is nested inside, but numbered second because its ( appears second.
A More Complex Example
const pattern = /(a(b(c)))/;
const text = "abc";
const result = pattern.exec(text);
console.log(result[1]); // "abc" - outermost group
console.log(result[2]); // "bc" - middle group
console.log(result[3]); // "c" - innermost group
The groups are numbered 1, 2, 3 from outermost to innermost, following the left-to-right order of opening parentheses.
Practical Use Case
const datePattern = /(\d{4})-(\d{2}(-\d{2}))/;
const date = "2024-03-15";
const result = datePattern.exec(date);
console.log(result[1]); // "2024" - year
console.log(result[2]); // "03-15" - month with day
console.log(result[3]); // "-15" - just the day part
Key Takeaway: Capture groups are numbered by the position of their opening parenthesis, reading left to right, regardless of nesting depth.