Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Groups, Backreferences and Lookaround

Replacing with Groups and Functions

Transform text with regex replace. Use replacement patterns $1, $&, $<name> and $$, write replacer functions with captures and offsets, and build safe templates, reformatters and sanitizers.

Matching is half of the story; the other half is changing the text. String.prototype.replace and replaceAll take a regex and a replacement, and the replacement can be a string with special tokens or a function. Together with groups this makes regex a powerful text transformation tool.

Replacement patterns

Inside the replacement string, these sequences are special:

Token Inserts
$& the whole match
$` the text before the match
$' the text after the match
$1 ... $99 the captured group with that number
$<name> the named group
$$ a literal dollar sign
Node.js Replacement tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A $ followed by something that is not a valid token stays as it is, which hides mistakes. In '$$$1.00' the first $$ is one dollar sign and $1 is the group. If your replacement text comes from users, escape its dollar signs (text.replaceAll('$', '$$$$')) or use a replacer function, which never interprets $.

Replacer functions

When the replacement is a function, it is called for each match with these arguments: the matched text, each captured group, the match offset, the whole input string, and, if the regex has named groups, a final groups object.

Node.js What the function receives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A function lets you compute the replacement: change case, do arithmetic, look up values, or format numbers.

Node.js Computing replacements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The template example returns the original match m for unknown keys, so {{missing}} stays visible instead of printing undefined.

Replacing with a map

A common pattern is replacing each of several words with its own value by using alternation and an object.

Node.js Multiple replacements in one pass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Doing it in one pass matters: two separate replace calls (cat to dog, then dog to cat) would turn everything into cat. One pass sees each original word exactly once.

Escaping HTML safely

Replacement functions are ideal for escaping, because each special character maps to an entity in a single pass.

Node.js Escape HTML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

replaceAll and the g flag

replaceAll(regex, ...) throws a TypeError if the regex lacks the g flag; with a plain string it replaces every occurrence literally.

Node.js replace versus replaceAll

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Order of evaluation and flow

flowchart LR
  A["Regex finds a match"] --> B{"Replacement is a function?"}
  B -- "yes" --> C["Call it with match, groups, offset, input"]
  B -- "no" --> D["Expand $1, $&, $<name>, $$"]
  C --> E["Insert the result"]
  D --> E
  E --> F["Continue after the match"]

The text between matches is copied unchanged.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 'John Smith'.replace(/(\w+) (\w+)/, '$2 $1') return?

    $1 is John, $2 is Smith, so they swap places.
  2. 2. How do you insert a literal dollar sign in a replacement string?

    In replacement strings, $$ produces one dollar sign.
  3. 3. Why use a single replace with a function instead of two chained replace calls to swap cat and dog?

    One pass visits each original word once. A second pass would undo or compound the first.
  4. 4. What is the first argument passed to a replacer function?

    The arguments are the match, then the groups, then the offset, then the whole string, then the named groups object.

Summary

  • Replacement strings support $1, $&, $`, $', $<name> and $$.
  • A replacer function gets the match, the groups, the offset, the input and the named groups; it never interprets $.
  • Use one pass with a map or lookup for multi-word substitutions; use functions to compute, format and escape.
  • replaceAll with a regex needs the g flag.

Next: Regex Flags in Depth