Course contentsShow
← JavaScript
Lesson 1706 of 2,72336. Regular ExpressionsFree lesson

Capture Groups with replace()

Use $1, $2, or $<name> in replacement strings to insert captured group values when replacing text.

Capture Groups with replace()

You'll learn how to reuse captured text when replacing patterns using $1, $2, or $<name> placeholders.

What This Unlocks

Once you've captured parts of a pattern with parentheses, the replace() method lets you reference those captured values in your replacement string. Instead of replacing matched text with static content, you can rearrange, modify, or selectively keep parts of what you matched.

The Syntax

In your replacement string, use:

  • $1, $2, $3... for numbered capture groups (first group, second group, etc.)
  • $<name> for named capture groups

JavaScript automatically substitutes these placeholders with the actual captured text.

Plain Example

Imagine finding a pattern like "John Doe" and wanting to reverse it to "Doe, John". You'd:

  1. Capture the first name in group 1
  2. Capture the last name in group 2
  3. Replace with "$2, $1"
const name = "John Doe";
const reversed = name.replace(/(\w+) (\w+)/, "$2, $1");
console.log(reversed);  // "Doe, John"

With named groups:

const name = "John Doe";
const reversed = name.replace(/(?<first>\w+) (?<last>\w+)/, "$<last>, $<first>");
console.log(reversed);  // "Doe, John"

The Analogy

Think of capture groups as containers that "catch" parts of text. When you use $1 or $<name> in the replacement, you're saying "pour the contents of that container here."

Key Takeaway: Use $1, $2, or $<name> in replace() to insert captured text into your replacement string, enabling powerful pattern transformations.