Regex Replace Capture Groups – Use $1 and $2 in JavaScript

Local only

Reuse captured substrings in a replacement string to reorder or reformat matched text without uploading the source.

13 chars · 1 line

5 chars · 1 line

Pattern matched the inputFlags: g

Regex replacement behavior

How to replace text with regex capture groups

JavaScript replacement strings can reuse captured substrings with tokens such as $1 and $2. The preloaded example captures a last name and first name, then reverses their order in Replace mode. This tool is free to use. No account or payment is required.

Last updated

What you can do here

  • Capture-group replacement
  • JavaScript $1/$2 tokens
  • Non-destructive preview
  • Configurable regex flags
  • Local text transformation
  • Browser-local processing

Steps

  1. Add capturing parentheses around the substrings the replacement needs to reuse.
  2. Reference those captures in the replacement field with $1, $2, and later numbers as needed.
  3. Preview the output and verify optional groups and punctuation against representative inputs before applying the pattern elsewhere.

Replacement token numbers follow capture group numbers

$1 refers to capture group 1, $2 to capture group 2, and so on. The complete matched text has separate replacement syntax, so capture numbering should be checked whenever grouping changes.

Capture-group replacement example

Reverse Last, First into First Last.

Pattern, replacement, input

(\w+),\s*(\w+)
$2 $1
Lovelace, Ada

Replaced text

Ada Lovelace

Common questions

Frequently asked questions

What does $1 mean in a JavaScript replacement?

It inserts the substring captured by the first capturing group in the regex.

Can I use named captures in replacement strings?

Yes. JavaScript also provides replacement syntax for named capture groups.

Why did my replacement group numbers change?

Adding or removing ordinary capturing groups can renumber later captures. Use non-capturing groups when parentheses are needed only for structure.

Debugging a specific Regex issue? Browse Regex troubleshooting.