Backreferences Match Duplicate Words
A backreference like \1 recalls what the first group captured, so repeated words and echoed tokens match without naming them in advance.
Code
// A backreference \1 inside the pattern recalls what group 1 captured,
// so repeated tokens match without knowing them in advance
const duplicate = /\b(\w+)\s+\1\b/;
console.log('duplicate caught:', 'the the same idea'.match(duplicate)[0]);
console.log('no repeat, no match:', duplicate.test('a single pass'));
// capture groups compare exactly: This this fails, This This would match
console.log('case matters:', duplicate.test('This this'));
// capture + backreference together rebuild the repeated token
const doubled = /(\d+)x\1/;
const match = 'id=7x7'.match(doubled);
console.log('group 1:', match[1], 'full match:', match[0]);
// named capture recalled with \k<name> reads better than a bare number
const echo = /(?<word>\w+) and \k<word>/;
console.log('named echo:', 'gone and gone'.match(echo).groups.word);Output
Captured from a sandboxed run of this snippet in the build pipeline.
duplicate caught: the the
no repeat, no match: false
case matters: false
group 1: 7 full match: 7x7
named echo: goneFollowing the data
Demo state sits in top-level bindings: duplicate, doubled, match, echo.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
Using it
The demo output is labeled (duplicate caught:, no repeat, no match:, case matters:); each label names the call that printed it.
Key statements
const match = 'id=7x7'.match(doubled);
Interactive Tools for This Topic
Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `duplicate`, `doubled`, `match`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.