Module lessons (2/4)
Basic replace and `$1`
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()andreplaceAll()referencing captured groups. - Use
$1,$2for 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
- 1Mental model: template with placeholders from capture groups
- 24 progressive step-by-step examples
- 3Guided practical exercises
- 4Quick check
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.