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.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// 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: gone

Following 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

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`.