JavaScript Regex Alternatives and Noncapturing Groups
Quick answer
Alternation expresses a choice between patterns; a noncapturing group controls scope without adding a capture result.
How it works
left|right tries alternatives in written order, subject to later matching requirements. (?:...) groups an expression without capturing it. Parentheses matter when anchoring alternatives: ^(?:red|blue)$ requires the entire input to be one of the two words.
console.log(/cat|catalog/.exec("catalog")[0], /catalog|cat/.exec("catalog")[0]);Expected output in Node.js:
cat catalogThe first successful alternative wins in these unanchored patterns.
console.log(/^(?:red|blue)$/.test("redwood"), /^(?:red|blue)$/.test("blue"));Expected output in Node.js:
false trueThe anchors enclose the grouped alternatives.
Common mistakes
^red|blue$ does not apply both boundaries to both alternatives. It means a prefix red or suffix blue.
Practice
Match a short allowlist of fixed command names without accepting prefixes or suffixes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Regex Alternatives and Noncapturing Groups — Knowledge Check
Apply the taught concept and predict the output.
Which syntax groups an alternative without capturing it?
Which metacharacter separates alternatives?
Why group alternatives before placing whole-input anchors?
What is the exact console output in JavaScript Regex Alternatives and Noncapturing Groups example 1?
console.log(/cat|catalog/.exec("catalog")[0], /catalog|cat/.exec("catalog")[0]);What is the exact console output in JavaScript Regex Alternatives and Noncapturing Groups example 2?
console.log(/^(?:red|blue)$/.test("redwood"), /^(?:red|blue)$/.test("blue"));