SyntaxStudy
Sign Up
JavaScript Intermediate 5 min read

Capturing Groups in Regex

Capturing Groups

Parentheses create capturing groups that extract matched portions. Access them via match() array or named groups with (?<name>...).

Example
// Numbered groups
const date = "2024-06-15";
const match = date.match(/(\d{4})-(\d{2})-(\d{2})/);
// match[1] = "2024", match[2] = "06", match[3] = "15"

// Named groups
const named = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
const { year, month, day } = named.groups;

// Non-capturing group (?:...)
/(?:https?):\/\//.test("https://"); // Groups but does not capture
Pro Tip

Use named groups (?...) instead of numbered groups when patterns have many groups — much easier to maintain.