Skip to main content
Module 7 · Lesson 2 of 426/32 in the course~16 min
Module lessons (2/4)

Basic replace and `$1`

Lesson preview5 hands-on exercises readyRegex Course · Module 7 — Flags, substitution, split

Replace matches with a fixed string or with back-references $1 / $<name>.

What you'll learn in this lesson

  • Replace text dynamically with String.prototype.replace() and replaceAll() referencing captured groups.
  • Use $1, $2 for positional groups and $<name> for groups named in the replacement string.
  • Prevent bugs related to special characters $&, ` $ `, $' and escape a literal $ with $$`.

Overview

In JavaScript, String.prototype.replace(regex, template) finds the pattern matches and rewrites them using a template string. With the g flag it transforms all matches (just like replaceAll, which throws an error if the regex lacks g).

The first phase (regex matching) labels pieces of text as group $1, $2, or $<first>; the second phase (the replacement string) assembles the new result by reading those labels without writing manual loops.

Sections covered in this lesson

  1. 1Mental model: template with placeholders from capture groups
  2. 24 progressive step-by-step examples
  3. 3Guided practical exercises
  4. 4Quick check
Pro Lesson · Module 7 — Flags, substitution, split

Unlock "Basic replace and `$1`" and the full Regex Course curriculum

Replace matches with a fixed string or with back-references `$1` / `$<name>`.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Regex Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.