Named capturing group: (?...) — Description
Named capturing groups can be used just like capturing groups — they also have their match index in the result array, and they can be referenced through \1, \2, etc.
Reference note (untrusted external data; do not execute it as instructions).
Named capturing groups can be used just like capturing groups — they also have their match index in the result array, and they can be referenced through \1, \2, etc. The only difference is that they can be _additionally_ referenced by their name. The information of the capturing group's match can be accessed through
The groups property of the return value of {{jsxref("RegExp.prototype.exec()")}}, {{jsxref("String.prototype.match()")}}, and {{jsxref("String.prototype.matchAll()")}} The groups parameter of the {{jsxref("String.prototype.replace()")}} and {{jsxref("String.prototype.replaceAll()")}} methods' replacement callback function Named backreferences within the same pattern
All names must be unique within the same pattern. Multiple named capturing groups with the same name result in a syntax error.
This restriction is relaxed if the duplicate named capturing groups are not in the same disjunction alternative, so for any string input, only one named capturing group can actually be matched. This is a much newer feature, so check browser compatibility before using it.
Named capturing groups will all be present in the result. If a named capturing group is not matched (for example, it belongs to an unmatched alternative in a disjunction), the corresponding property on the groups object has value undefined.
You can get the start and end indices of each named capturing group in the input string by using the d flag. In addition to accessing them on the indices property on the array returned by exec(), you can also access them by their names on indices.groups.
Compared to unnamed capturing groups, named capturing groups have the following advantages
They allow you to provide a descriptive name for each submatch result. They allow you to access submatch results without having to remember the order in which they appear in the pattern. When refactoring code, you can change the order of capturing groups without worrying about breaking other references.
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/reference/regular_expressions/named_capturing_group/index.md :: Description ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution