Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Patterns for Text Processing

Search and Replace Recipes

Master regex replacement. Learn $1, $<name> and $& substitutions, replacer functions, replaceAll, and practical recipes for case conversion, trimming, masking, reformatting and escaping.

Find-and-replace is where regular expressions earn their keep. A plain string replace can swap one word for another. A regex replace can reorder dates, mask card numbers, convert snake_case to camelCase and clean up whitespace in one pass, because the replacement can reuse what was matched.

JavaScript's String.prototype.replace takes a pattern and either a replacement string with special tokens or a function. Other languages offer the same two styles with slightly different tokens.

Replacement tokens

In a replacement string, these sequences are special:

Token Meaning
$1, $2 ... Text captured by numbered group
$<name> Text captured by named group
$& The entire match
$` Text before the match
$' Text after the match
$$ A literal dollar sign
Node.js Reordering with captured groups

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.

If you want to insert user text containing $ without it being interpreted, pass a function instead of a string, or escape the dollars with text.replaceAll("$", "$$$$"). Functions are the safer default.

Replacer functions

A function receives the match, then each group, then the offset, then the whole string, and finally an object of named groups (if any). Whatever it returns replaces the match. This unlocks logic: lookups, arithmetic, conditionals.

Node.js Computing the replacement

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 global rule

replaceAll requires either a string pattern or a regex with the g flag; using a regex without g throws a TypeError. With a string pattern it replaces every literal occurrence without any regex escaping.

JavaScript
"a.b.c".replaceAll(".", "-");        // "a-b-c" (literal dot)
"a.b.c".replace(/\./g, "-");         // same with a regex
"a.b.c".replace(".", "-");           // "a-b.c" (string pattern, first only)

Recipes

Node.js Ten everyday 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.

A few notes on those:

  • Recipe 6 uses \B (not at a word boundary) and a lookahead to find positions before groups of three digits. It would also insert commas into a long fraction such as 0.123456, so for real formatting use Intl.NumberFormat.
  • Recipe 8 is the standard escape function. RegExp.escape is arriving in newer JavaScript runtimes, so check your target before relying on it.
  • Recipe 7 is fine for display text, but regex is not an HTML sanitizer; use a real sanitizer for security.

Replacing in other languages

The ideas are universal; only the spelling changes.

Language Call Group reference
JavaScript s.replace(re, "$1") $1, $<name>
Python re.sub(pat, r"\1", s) \1, \g<name>
PHP preg_replace($pat, '$1', $s) $1, \1
Java s.replaceAll(pat, "$1") $1, ${name}
sed s/pat/\1/g \1 (BRE)

You can see these side by side in regex in other languages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does "Ada Lovelace".replace(/(\w+) (\w+)/, "$2 $1") return?

    $1 and $2 refer to the captured words, so the replacement swaps them.
  2. 2. Why might you pass a function to replace instead of a string?

    A function can run any logic, and its return value is inserted literally, so user text containing a dollar sign is safe.
  3. 3. What happens with "a.b".replaceAll(/./, "-")?

    replaceAll requires a global regex when given a regular expression.
  4. 4. What does the token $& insert?

    $& stands for the entire match; use it to wrap or repeat what was found.

Summary

  • Replacement strings can reuse captures with $1, $<name> and $&; $$ is a literal dollar.
  • A replacer function receives the match, groups, offset, string and named groups, and returns the new text.
  • replace without g changes only the first match; replaceAll needs a string or a g regex.
  • Escape user text before building a regex from it.
  • Many text cleanups (whitespace, case conversion, masking, slugs) are one-line replacements.

Next: Splitting and Tokenizing Text