JavaScript Reference ยท RegExp
Regular expression capture groups
Reference for JavaScript regex groups: numbered, named and non-capturing groups, alternation, backreferences in replace() and reading results with exec().
Parentheses in a regular expression do two jobs: they group part of the pattern so that quantifiers and alternation apply to the whole part, and they capture the text the group matched so you can read it afterwards. JavaScript has three kinds of groups: numbered capturing groups (...), named capturing groups (?<name>...) and non-capturing groups (?:...).
This is a concept page. Captured text is available in the result of exec() and match(), in matchAll(), and in the replacement of replace() through $1 or $<name>.
const match = /(?<year>\d{4})-(?<month>\d{2})/.exec("2026-03"); match.groups.year; // "2026" match[2]; // "03"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Kinds of groups
| Syntax | Description |
|---|---|
(x) |
Capturing group. Numbered from 1 in the order the opening parentheses appear. |
(?<name>x) |
Named capturing group. Also numbered. Read it from match.groups.name. |
(?:x) |
Non-capturing group. Groups for quantifiers or alternation only. |
\1, \2 |
Backreference to a numbered group inside the same pattern. |
\k<name> |
Backreference to a named group. |
$1, $<name> |
Insert a group in a replace() replacement string. $& is the whole match. |
Usage notes
- Numbering follows opening parentheses, left to right, including nested groups. Adding a group early shifts all later numbers, which is why named groups age better.
- Names must be unique in a pattern (a newer feature allows the same name in different alternatives, so check a compatibility table) and are identifiers such as
year. - A non-participating group is
undefined, not an empty string. Use?? ""to supply a default. - Repeated groups keep only the last capture. To collect every repetition, use
matchAll()with a simpler pattern. match()withoutgreturns the same detailed result asexec(); withgit returns only the whole matches, no groups. UsematchAll()to get groups for every match.groupsisundefinedwhen the pattern has no named group.- Use non-capturing groups when you do not need the text, to keep numbers stable and the regex a little faster.
- Backreference to a group that has not matched yet matches the empty string.
- In
replace(), a literal$in the replacement must be written$$.
Browser support
Numbered and non-capturing groups work everywhere. Named groups are supported by all current browsers; check a compatibility table for very old ones.