Accessing Captured Values with exec()
You'll learn how to extract captured group values from regex matches using the exec() method.
You've already seen how to create capture groups with parentheses in your regex patterns. Now it's time to actually use the values they capture.
How exec() Returns Captures
When you call regex.exec(string) and find a match, it returns an array with a special structure:
- Index 0: The full matched text
- Index 1, 2, 3...: The captured values from each group (in order)
Think of it like a treasure chest: the whole chest is your full match, but inside are compartments (captures) containing specific pieces you're interested in.
Example Pattern
const datePattern = /(\d{4})-(\d{2})-(\d{2})/;
const text = "Event date: 2024-03-15";
const result = datePattern.exec(text);
console.log(result[0]); // "2024-03-15" (full match)
console.log(result[1]); // "2024" (first capture group - year)
console.log(result[2]); // "03" (second capture group - month)
console.log(result[3]); // "15" (third capture group - day)
Multiple Groups in Action
const emailPattern = /(\w+)@(\w+)\.(\w+)/;
const email = "user@example.com";
const match = emailPattern.exec(email);
console.log(match[0]); // "user@example.com"
console.log(match[1]); // "user"
console.log(match[2]); // "example"
console.log(match[3]); // "com"
The array gives you direct access to dissect your match into meaningful parts—perfect for parsing structured data like dates, URLs, or email addresses.
Key Takeaway: regex.exec() returns an array where index 0 is the full match, and indexes 1+ contain each captured group's value in the order they appear in your pattern.