Module lessons (3/4)
Replace with a callback
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
groupsto 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
- 1Mental model: map function dedicated to matches
- 24 progressive examples step by step
- 3Guided practical exercises
- 4Quick check
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.