Skip to content

JavaScript regex named group

  • by

JavaScript regular expressions support named capture groups, which allow you to assign names to groups within the pattern. Named capture groups provide a more expressive and readable way to extract and manipulate portions of a string.

In JavaScript regular expressions, the syntax for named capture groups is as follows:

/(?<name>pattern)/
  • ?<name> is the part where you assign a name to the capture group.
  • name is the name you want to assign to the capture group. It can be any valid JavaScript identifier.
  • pattern is the regular expression pattern that you want to match and capture.

To create a named capture group in JavaScript, you can use the syntax (?<name>pattern), where name is the name you want to assign to the group, and pattern is the regular expression pattern for that group.

JavaScript regex named group example

Simple example code that demonstrates how to use named capture groups in JavaScript:

const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = regex.exec('2023-06-14');

console.log(match.groups.year);  
console.log(match.groups.month);
console.log(match.groups.day);  

Output:

JavaScript regex named group

You can access the captured values by using match.groups.name, where name is the name of the capture group. In the example above, match.groups.year gives you the captured year, match.groups.month gives you the captured month, and match.groups.day gives you the captured day.

Note: named capture groups are supported in ECMAScript 2018 (ES9) and later versions.

Comment if you have any doubts or suggestions on this Js RegEx topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *