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.
Code
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=def456Where 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.PII Text CensorDetect and redact emails, phone numbers, credit card numbers, and US Social Security numbers in text, reporting how many of each were masked.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.