How do you access the matched groups in a JavaScript regular expression?
In JavaScript, you can capture parts of a string (substrings) that match certain parts of a regular expression, and then access these captured groups via the match()
, exec()
, or matchAll()
methods. Below are the most common ways to retrieve matched groups—both with and without named capturing groups.
1. Using String.prototype.match()
Basic Capturing Groups
const str = 'My lucky number is 42.'; const regex = /(\d+)/; // parentheses create a capturing group const result = str.match(regex); console.log(result[0]); // "42" (the entire match) console.log(result[1]); // "42" (the first capturing group)
result[0]
is always the full match.result[1]
is the first capturing group,result[2]
would be the second, and so on.
Named Capturing Groups (ES2018+)
const str = 'My lucky number is 42.'; const regex = /(?<digits>\d+)/; const result = str.match(regex); console.log(result[0]); // "42" (full match) console.log(result.groups.digits); // "42" (named group)
- You define a named group with
?<groupName>
. - The matched group is available via
result.groups.groupName
.
Note: Named capturing groups require modern environments that support ES2018+ features.
2. Using RegExp.prototype.exec()
This method returns an array of matches, similar to match()
, but is often used in a loop for iterative matching (e.g., with the /g
flag).
const str = 'Numbers: 42 and 7.'; const regex = /(\d+)/g; let match; while ((match = regex.exec(str)) !== null) { console.log('Full match:', match[0]); console.log('Group 1:', match[1]); }
match[0]
: the overall matched substring.match[1]
: the substring captured by the first group.exec()
updatesregex.lastIndex
as it finds successive matches.
3. Using String.prototype.matchAll()
(ES2020+)
For modern JavaScript, matchAll()
is a convenient way to get all matches and capturing groups in an iterable form:
const str = 'Numbers: 42 and 7.'; const regex = /(\d+)/g; for (const match of str.matchAll(regex)) { console.log('Full match:', match[0]); console.log('Group 1:', match[1]); }
- Returns an iterator of match arrays (including capturing groups).
- No need for manual
while
loops or updatinglastIndex
.
Key Points
- Capture vs. Non-Capture: Parentheses
( ... )
capture the sub-match for referencing, while non-capturing groups(?: ... )
group tokens without storing. - Indexing:
match[n]
corresponds to the nth capturing group in order from left to right. - Named Groups: Provide more readable code when dealing with multiple complex groups, but require a more recent JS environment (ES2018+).
Bonus: Level Up Your JavaScript and Coding Skills
Mastering regex is just one piece of the puzzle. To truly excel in front-end or full-stack roles, consider strengthening your JavaScript foundation and coding interview skills. We recommend checking out these courses from DesignGurus.io:
-
Grokking JavaScript Fundamentals
Deepen your understanding of closures, prototypes, async/await, and other crucial aspects of modern JavaScript. -
Grokking the Coding Interview: Patterns for Coding Questions
Sharpen your problem-solving approach with real-world coding patterns—vital for technical interviews and daily engineering challenges.
If you want personalized feedback, consider the Mock Interview services (Coding Mock Interview or System Design Mock Interview) with ex-FAANG engineers. Also, explore the DesignGurus.io YouTube channel for free tutorials on system design, coding patterns, and more.
Final Thoughts
To access matched groups in JavaScript:
- Use
match()
,exec()
, ormatchAll()
depending on whether you need a single match, iterative searching, or an ES2020+ approach with an iterable. - Numbered capturing groups are accessed by array indices.
- Named capturing groups (ES2018+) provide better clarity and are accessed with
result.groups.groupName
.
Understanding how to extract and process regex captures is vital for tasks like data parsing, form validation, and text manipulation in JavaScript.