How to Use Capture Groups in JavaScript Regex: Syntax and Examples
In JavaScript, use
(...) parentheses in a regex to create capture groups that save matched parts of a string. Access these groups via the match() method's returned array or with RegExp.exec() to extract specific substrings.Syntax
Capture groups are created by wrapping part of a regex pattern in parentheses (...). Each group captures the text matched inside it. You can access these groups by their order starting at 1.
/(pattern)/: Defines a capture group.matchResult[0]: The full matched string.matchResult[1]: Text matched by the first capture group.- Multiple groups can be used to capture multiple parts.
javascript
/(\w+)@(\w+)\.(\w+)/
Example
This example shows how to extract the username, domain, and extension from an email address using capture groups.
javascript
const email = 'alice@example.com'; const regex = /(\w+)@(\w+)\.(\w+)/; const result = email.match(regex); if (result) { console.log('Full match:', result[0]); console.log('Username:', result[1]); console.log('Domain:', result[2]); console.log('Extension:', result[3]); } else { console.log('No match found'); }
Output
Full match: alice@example.com
Username: alice
Domain: example
Extension: com
Common Pitfalls
Common mistakes include forgetting to escape special characters, not checking if the match is null before accessing groups, and confusing group indexes.
Also, using non-capturing groups (?:...) when you don't want to capture can avoid confusion.
javascript
const text = 'Price: $100'; const wrongRegex = /\$(\d+)/; // Correct const noEscapeRegex = /$(\d+)/; // Wrong, $ is special const result1 = text.match(wrongRegex); const result2 = text.match(noEscapeRegex); console.log(result1 ? result1[1] : 'No match'); console.log(result2 ? result2[1] : 'No match');
Output
100
No match
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Capture Group | Parentheses to capture part of match | /(abc)/ |
| Access Group | Use match array index starting at 1 | result[1] |
| Non-capturing Group | Group without capturing | /(?:abc)/ |
| Escape Special Char | Use backslash to escape | /\$/ |
| Check Match | Always check if match is null | if(match) {...} |
Key Takeaways
Use parentheses ( ... ) in regex to create capture groups in JavaScript.
Access captured text via the array returned by match() or exec(), starting at index 1.
Always check if the regex matched before accessing capture groups to avoid errors.
Escape special characters like . and $ inside regex patterns.
Use non-capturing groups (?:...) when you want grouping without capturing.