0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Named Groups in JavaScript Regex

In JavaScript, you can use named groups in regex by writing (?pattern) inside your regular expression. After matching, access the captured groups by name using the groups property on the match result object.
📐

Syntax

The syntax for named groups in JavaScript regex is (?pattern). Here, name is the label you assign to the group, and pattern is the part of the regex you want to capture.

When you run the regex, the matched groups can be accessed by their name through the groups property of the match result.

javascript
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
💻

Example

This example shows how to extract year, month, and day from a date string using named groups in a regex. The matched groups are accessed by their names from the groups property.

javascript
const date = '2024-06-15';
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = date.match(regex);

if (match) {
  console.log(`Year: ${match.groups.year}`);
  console.log(`Month: ${match.groups.month}`);
  console.log(`Day: ${match.groups.day}`);
} else {
  console.log('No match found');
}
Output
Year: 2024 Month: 06 Day: 15
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to use the groups property to access named groups; trying to access them by index instead.
  • Using named groups in environments that do not support them (older browsers or Node.js versions before 10).
  • Incorrect syntax like missing the ?< and > around the group name.

Always ensure your environment supports named groups and use the correct syntax.

javascript
/* Wrong way: trying to access named groups by index */
const regexWrong = /(?<name>\w+)/;
const resultWrong = 'Alice'.match(regexWrong);
console.log(resultWrong[1]); // Works but no name
console.log(resultWrong.groups.name); // Correct way

/* Correct way: */
const regexRight = /(?<name>\w+)/;
const resultRight = 'Alice'.match(regexRight);
console.log(resultRight.groups.name); // Outputs 'Alice'
Output
Alice Alice
📊

Quick Reference

  • Syntax: (?pattern)
  • Access groups: Use match.groups.name
  • Supported in: Modern browsers and Node.js 10+
  • Use case: Makes regex matches easier to read and maintain

Key Takeaways

Use (?pattern) to create named groups in JavaScript regex.
Access matched groups by name using the groups property on the match result.
Named groups improve code readability by labeling parts of your regex.
Ensure your JavaScript environment supports named groups (Node.js 10+ or modern browsers).
Avoid accessing named groups by index; always use the groups property.