Use a non-capturing group when parentheses should group regex terms but their matched text should not appear as a capture. Add `?:` immediately after the opening parenthesis: `(?:pattern)`. This changes the match array, not what the pattern matches. section 12.4.1
In practice:
- `(?: of (\S+))?` groups the optional ` of ` and clan-name pattern without capturing the whole group; the inner ` (\S+)` still captures the clan name. section 12.4.1
- Omitting `?:` lets the group capture. With a repeated capturing group, the capture holds its last result; use a non-capturing group when that value is not needed. section 12.6.3
An optional clan name
In `/(\S+)(?: of (\S+))?/`, matching `Hattori of Iga` gives the full match, `Hattori`, and `Iga` as the match array’s three entries. Matching `Yoshi` leaves the clan capture `undefined`; the non-capturing group adds no entry. section 12.4.1
Listing 12.5 Nested, optional, and non-capturing groups
const ninjaTitleRegex = /(\S+)(?: of (\S+))?/; #A
const ninjaTitle = "Hattori of Iga";
const found = ninjaTitle.match(ninjaTitleRegex); #B
if (found === null) {
console.assert(false, "Match expected");
} else {
const [match, name, clan] = found; #C
console.assert(
match === "Hattori of Iga",
"The full match is 'Hattori of Iga'",
);
console.assert(
name === "Hattori",
"The first capture group is 'Hattori'",
);
console.assert(
clan === "Iga",
"The second capture group is 'Iga'",
);
}
See the complete JavaScript example and its assertions for the full match and individual captures. section 12.4.1



