Course contentsShow
← JavaScript
Lesson 1703 of 2,72336. Regular ExpressionsFree lesson

Named Capture Groups

Use (?<name>...) syntax to give capture groups descriptive names for clearer code and access via .groups.

Named Capture Groups

You'll learn how to give your regex capture groups meaningful names instead of relying on numbered positions.

The Problem with Numbered Groups

In the last lesson, you learned how to create capture groups with parentheses and access them by their numeric index (1, 2, 3, etc.). This works, but reading match[1] or match[2] in your code doesn't tell you what you're capturing — you have to trace back to the regex pattern to remember.

Named Capture Groups: Labels for Clarity

JavaScript allows you to give capture groups descriptive names using the syntax (?<name>...). The angle brackets contain your chosen name, and everything inside the parentheses is captured just like before.

Instead of remembering "position 2 is the month," you can name it month and access it as groups.month. It's like labeling boxes instead of just numbering them.

How to Use Named Groups

const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const result = pattern.exec('2024-03-15');

console.log(result[1]);           // "2024" (still works by index)
console.log(result.groups.year);  // "2024" (named access)
console.log(result.groups.month); // "03"
console.log(result.groups.day);   // "15"

The captured values are accessible both ways: by numeric index and via the .groups object. The .groups object is automatically created when you use named capture groups.

When to Use Named Groups

Use named groups when:

  • Your pattern has multiple captures and clarity matters
  • Other developers (or future you) will read the code
  • You're extracting structured data like dates, URLs, or records

Key Takeaway: Named capture groups with (?<name>...) let you access captures via .groups.name for self-documenting, readable code instead of cryptic numeric indices.