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.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
// 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
$& REDACTED

Inside 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

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`.