实现说明
各个操作都建立在顶层绑定之上:log、redacted、usd。
使用要点
- 演示输出是带标签的(
price),每个操作都会留下自己的一行标注。
常见问题
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 状态都挂在模块顶层:log、redacted、usd。
核心语句
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");
代码示例
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}`));