replace Accepts a Replacer Function

Compute replacements at runtime with a function passed to replace, where the callback receives the match, capture groups, offset, and the full string.

JavascriptSecurity Boundaries

Code

snippet
const log = 'user id=42 token=abc123; user id=7 token=def456';

// 第二参为函数:match、捕获组、offset、原串全部可用
const redacted = log.replace(/token=(\w+)/g, (match, token, offset, full) => {
  return `token=<${token.length} chars> at ${offset}`;
});
console.log(redacted);

// $& 在字符串替换里有特殊语义,函数返回值里则是纯文本
console.log("price".replace("ice", "$&$&"));   // 字面拼接

// 经典陷阱:数字替换不会自动转义 $
const usd = "100".replace(/\d+/, (n) => n + " USD");
console.log(usd);

// 只替换第一处时不带 g 标志,函数同样生效
console.log(log.replace(/id=(\d+)/, (m, id) => `id=${Number(id) + 1000}`));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

user id=42 token=<6 chars> at 11; user id=7 token=<6 chars> at 35
priceice
100 USD
user id=1042 token=abc123; user id=7 token=def456

Where the behavior sits

Top-level bindings log, redacted, usd hold the demo state — nothing sits inside a function scope.

Points of care

  • The package manager never enters the picture for this snippet.

Putting it to use

The demo output is labeled (price); each label names the call that printed it.

Core lines

const redacted = log.replace(/token=(\w+)/g, (match, token, offset, full) => {
  return `token=<${token.length} chars> at ${offset}`;
});
const usd = "100".replace(/\d+/, (n) => n + " USD");

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `log`, `redacted`, `usd`.