replace Callbacks Build Substitutions In Code
replace with a callback builds substitutions from the match and its capture groups, and returns them literally where $ sequences would have expanded.
Code
// With a callback replacer the returned string is used literally —
// $ sequences inside it have no special meaning
const log = 'status=200 time=42ms status=500 time=118ms';
const marked = log.replace(/status=(\d{3})/g, (_match, code) => {
return Number(code) >= 400 ? '[ERR]' : '[OK]';
});
console.log(marked);
// The callback receives the full match, each capture group, the offset,
// and the original string — enough to build any substitution in code
const route = 'GET /users/42/posts/7';
const rewritten = route.replace(
/\/users\/(\d+)\/posts\/(\d+)/,
(_match, userId, postId) => '/print/users/' + userId + '/posts/' + postId,
);
console.log(rewritten);
// Compare with a string replacement, where $& expands to the whole match:
console.log('token=abc123'.replace(/token=\w+/, '$& REDACTED'));
// A callback returning the same text keeps "$&" as plain characters:
console.log('token=abc123'.replace(/token=\w+/, () => '$& REDACTED'));Output
Captured from a sandboxed run of this snippet in the build pipeline.
[OK] time=42ms [ERR] time=118ms
GET /print/users/42/posts/7
token=abc123 REDACTED
$& REDACTEDInside the snippet
The demo state is four bindings: log (the raw status string), marked (after the callback replacer runs), plus route and rewritten further down.
Points of care
- Everything it calls is documented as part of the language core.
Putting it to use
Output lines are prefixed (token=abc123), making each step’s effect easy to spot.
Core lines
const marked = log.replace(/status=(\d{3})/g, (_match, code) => {
return Number(code) >= 400 ? '[ERR]' : '[OK]';
});
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `log`, `marked`, `route`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.