RegExp Named Capturing Groups (?<name>x)
Example
const text = "Name: John Doe";
// Using named capturing groups
const regex = /(?<firstName>\w+) (?<lastName>\w+)/;
const match = text.match(regex);
let fName = match.groups.firstName;
let lName = match.groups.lastName;
Try it Yourself »
Explained
- (?<firstName>\w+) captures a word and labels it firstName
- (?<lastName>\w+) does the same for lastName
- text.match() returns an array with a groups property
- match.groups() returns an object:
{firstName:"John", lastName:"Doe" }
When using a regular expression with capturing groups, the match() method of a string returns a result array that includes a groups property. This groups property is an object that holds the matches for named capturing groups.
Syntax
new RegExp("(?<name>x)")
or simply:
/(?<name>x)/
Regular Expression Methods
Regular Expression Search and Replace can be done with different methods.
These are the most common:
String Methods
Method | Description |
---|---|
match(regexp) | Returns an Array of results |
matchAll(regexp) | Returns an Iterator of results |
replace(regexp, s) | Returns a new String |
replaceAll(regexp, s) | Returns a new String |
search(regexp) | Returns the index of the first match |
split(regexp) | Returns an Array of results |
regexp Methods
Method | Description |
---|---|
regexp.exec() | Returns an Iterator of results |
regexp.test() | Returns true or false |
Browser Support
/(?<name>x)/
is a JavaScript 2018 feature.
ES 2018 is supported in all modern browsers since June 2020:
Chrome 63 | Edge 79 | Firefox 78 | Safari 12 | Opera 50 |
Des 2017 | Jan 2020 | Jun 2020 | Sep 2018 | Jan 2018 |