Regex - reusing patterns to capture groups in JavaScript?

Regular expressions can use backreferences to capture groups and reuse them later in the pattern. The syntax \1, \2, etc., refers to previously captured groups.

How Backreferences Work

When you create a group with parentheses (), the regex engine remembers the matched content. You can reference this captured content later using \1 for the first group, \2 for the second, and so on.

Syntax

/^(pattern1)(pattern2)\1\2$/
// \1 matches the same text as the first group
// \2 matches the same text as the second group

Example: Matching Repeated Patterns

var groupValues1 = "10 10 10";
var groupValues2 = "10 10 10 10";
var groupValues3 = "10 10";

// Pattern: (digits)(space)(same digits)(same space)(same digits again)
var regularExpression = /^(\d+)(\s)\1\2\1$/;

var isValidGroup1 = regularExpression.test(groupValues1);
var isValidGroup2 = regularExpression.test(groupValues2);
var isValidGroup3 = regularExpression.test(groupValues3);

if (isValidGroup1 == true)
    console.log("This is a valid group=" + groupValues1);
else
    console.log("This is not a valid group=" + groupValues1);

if (isValidGroup2 == true)
    console.log("This is a valid group=" + groupValues2);
else
    console.log("This is not a valid group=" + groupValues2);

if (isValidGroup3 == true)
    console.log("This is a valid group=" + groupValues3);
else
    console.log("This is not a valid group=" + groupValues3);
This is a valid group=10 10 10
This is not a valid group=10 10 10 10
This is not a valid group=10 10

Pattern Breakdown

Pattern Part Description Matches
(\d+) Group 1: One or more digits "10"
(\s) Group 2: A space character " "
\1 Same as Group 1 "10" (must match exactly)
\2 Same as Group 2 " " (must match exactly)
\1 Same as Group 1 again "10" (must match exactly)

Another Example: Word Repetition

var pattern = /^(\w+)-\1$/;  // word-sameword

console.log(pattern.test("hello-hello"));  // true
console.log(pattern.test("test-test"));    // true
console.log(pattern.test("hello-world"));  // false
console.log(pattern.test("abc-123"));      // false
true
true
false
false

Key Points

  • \1 references the first captured group ()
  • \2 references the second captured group, and so on
  • The backreference must match the exact same text, not just the same pattern
  • Useful for validating repeated patterns or finding duplicated words

Conclusion

Backreferences allow you to reuse captured groups within regex patterns. Use \1, \2, etc., to match previously captured content exactly.

Updated on: 2026-03-15T23:18:59+05:30

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements