Skip to main content
Module 7 · Lesson 3 of 427/32 in the course~18 min
Module lessons (3/4)

Replace with a callback

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

Substitution function: transform every match with arbitrary JS code, access to groups.

What you'll learn in this lesson

  • Pass a callback function to String.prototype.replace(regex, fn) to perform dynamic logic, calculations, and transformations on each match.
  • Know the exact signature of the arguments received from the callback: (match, p1, p2, ..., offset, input, groups).
  • Use the last argument groups to conveniently access named groups without depending on indexes.

Overview

When a pattern string like '$2/$1' isn't enough — for example, you need to convert units, obfuscate sensitive data, do dictionary lookups, or perform mathematical calculations — you can pass a callback function as the second argument of .replace(regex, callback).

JavaScript finds each pattern match and invokes your callback once for each match, injecting the returned result in place of the original text.

Sections covered in this lesson

  1. 1Mental model: map function dedicated to matches
  2. 24 progressive examples step by step
  3. 3Guided practical exercises
  4. 4Quick check
Pro Lesson · Module 7 — Flags, substitution, split

Unlock "Replace with a callback" and the full Regex Course curriculum

Substitution function: transform every match with arbitrary JS code, access to groups.

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.