liveBook · Manning

Alternation

As explained in Secrets of the JavaScript Ninja, Second Edition

A regular-expression construct that matches one of several alternative subpatterns.

Alternation lets a regular expression match one of several alternatives. The pipe (`|`) separates them: `/a|b/` matches either `a` or `b`. Group alternatives when a quantifier should apply to them, as in `/(ab)+|(cd)+/`. section 10.2.2

Listing 10.11. Matching all characters, including newlines
 const html = "<b>Hello</b>\n<i>world!</i>";                     #A
 assert(/.*/.exec(html)[0] === "<b>Hello</b>",                   #B
         "A normal capture doesn't handle endlines.");
 assert(/[\S\s]*/.exec(html)[0] ===                              #C
         "<b>Hello</b>\n<i>world!</i>",                          #C
         "Matching everything with a character set.");           #C
 assert(/(?:.|\s)*/.exec(html)[0] ===                            #D
         "<b>Hello</b>\n<i>world!</i>",                          #D
         "Using a non-capturing group to match everything.");    #D

Compare two ways to match across newlines: `/(?:.|\s)*/` uses alternation, while `/[\S\s]*/` uses a character class and is described as the generally optimal solution. section 10.6.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines the pipe operator and demonstrates grouped alternatives and a newline-matching workaround.
Examples
Uses `/a|b/`, `/(ab)+|(cd)+/`, and `/(?:.|\s)*/` as examples.
What you can do after
Build regular-expression patterns that match either of several alternatives.
How it connects
Connects alternation with grouping, quantifiers, character classes, and non-capturing groups.

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.