liveBook · Manning

Noncapturing group

As explained in Secrets of the JavaScript Ninja, Second Edition

A regular-expression group that combines subpatterns without recording their matched text as a capture.

Use `(?:...)` when parentheses need to group a pattern but their matched text should not become a capture. This keeps captures focused on the results you actually need; the trade-off is that complex patterns can become a little harder to read. section 10.4.4

Repeat a prefix without an extra capture

In `/((?:ninja-)+)sword/`, the inner group lets `+` repeat `ninja-` without capturing it separately. The outer group captures the full prefix. section 10.4.4

Listing 10.8. Grouping without capturing
const pattern = /((?:ninja-)+)sword/;                               #A
const ninjas = "ninja-ninja-sword".match(pattern);

assert(ninjas.length === 2,"Only one capture was returned.");
assert(ninjas[1] === "ninja-ninja-",
      "Matched both words, without any extra capture.");

See the pattern return one capture for `ninja-ninja-`, rather than an additional capture for the repeated group. section 10.4.4

Noncapturing groups can also group alternatives: `(?:.|\s)*` matches across newlines without creating an unintended capture. The character-class alternative `/[\S\s]*/` is described as generally optimal. section 10.6.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines `(?:...)`, demonstrates its effect on captures, and notes readability and performance trade-offs without detailing engine internals.
Examples
Demonstrates repeated `ninja-` prefixes before `sword` and alternation that matches newline-containing HTML.
What you can do after
Build it from scratch by grouping repeated or alternative pattern text with `(?:...)` while preserving intended captures.
How it connects
Connects capturing groups and quantifiers with alternation and newline matching.

Also explained in

Compare how 3 books explain noncapturing group →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.