Regex Replace Patterns — Using Capture Groups in Replacements

Learn how to use regex capture groups in replacement strings with $1, $2, and named references. Covers JavaScript replace(), replaceAll(), and common transformations.

Groups

Detailed Explanation

Regex Replace Patterns

The real power of capture groups shines in replacement operations. JavaScript's String.prototype.replace() and replaceAll() accept regex patterns with group references.

Basic Group References

In replacement strings, $1, $2, etc. refer to captured groups:

"2024-01-15".replace(
  /(\d{4})-(\d{2})-(\d{2})/,
  "$2/$3/$1"
)
// Result: "01/15/2024"

Named Group References

With named groups, use $<name> in the replacement:

"John Smith".replace(
  /(?<first>\w+) (?<last>\w+)/,
  "$<last>, $<first>"
)
// Result: "Smith, John"

Special Replacement Tokens

Token Inserts
$$ Literal "$"
$& Entire matched substring
$\x60 Text before the match
$' Text after the match
$1...$9 Captured group by number
$<name> Named captured group

Function Replacements

For complex transformations, pass a function:

"hello world".replace(/\b\w/g, (char) => char.toUpperCase())
// Result: "Hello World"

Common Replace Operations

  • Remove whitespace: str.replace(/\s+/g, "")
  • Normalize spaces: str.replace(/\s+/g, " ")
  • Convert camelCase to kebab-case: str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()
  • Wrap words in tags: str.replace(/\b(\w+)\b/g, "<span>$1</span>")
  • Strip HTML tags: str.replace(/<[^>]+>/g, "")

Use Case

You are transforming text formats, such as converting date formats, reordering name fields, normalizing whitespace, converting between naming conventions (camelCase to kebab-case), or sanitizing user input.

Try It — Regex Cheat Sheet

Open full tool