JavaScript Regex Capturing and Named Groups
Quick answer
Capturing groups preserve matched subexpressions so the program can extract structured parts of text. Named captures make those parts accessible by meaningful keys.
How it works
(pattern) captures by number, counted by opening parentheses; (?<name>pattern) also exposes a named capture through the result groups object. and \k<name> refer back to captured text inside a pattern. exec returns an array-like match result whose index 0 is the whole match. A group that did not participate has value undefined.
const m = /([A-Z]+)-(\d+)/.exec("AB-42");console.log(m[0], m[1], m[2]);Expected output in Node.js:
AB-42 AB 42The full match precedes the numbered captures.
const m = /(?<word>[a-z]+)-\k<word>/.exec("go-go");console.log(m.groups.word);Expected output in Node.js:
goThe named backreference requires the captured text again.
Common mistakes
Check for null before reading groups. Parentheses used only for grouping should usually be noncapturing.
Practice
Extract two fields from a fixed-format identifier and handle a failed match.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Regex Capturing and Named Groups — Knowledge Check
Apply the taught concept and predict the output.
Where is the entire successful exec match stored?
Which syntax declares a named capture called id?
What does a backreference require at its matching position?
What is the exact console output in JavaScript Regex Capturing and Named Groups example 1?
const m = /([A-Z]+)-(\d+)/.exec("AB-42");console.log(m[0], m[1], m[2]);What is the exact console output in JavaScript Regex Capturing and Named Groups example 2?
const m = /(?<word>[a-z]+)-\k<word>/.exec("go-go");console.log(m.groups.word);