← 中文资源

简体中文版本

replace 回调在代码里构造替换文本

replace 的回调形式用匹配与捕获组在代码里构造替换,返回值原样进入结果——$ 序列不再有特殊含义,与字符串替换形成对照。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

[OK] time=42ms [ERR] time=118ms
GET /print/users/42/posts/7
token=abc123 REDACTED
$& REDACTED

实现说明

顶层就这几处状态:log、marked、route、rewritten。

使用要点

  • 直接运行文件,输出会带上标签,比如 token=abc123——输出的每一行都能指回产生它的那次调用。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 跨调用保留的状态放在这些顶层绑定里:log、marked、route。

核心语句

const marked = log.replace(/status=(\d{3})/g, (_match, code) => {
  return Number(code) >= 400 ? '[ERR]' : '[OK]';
});

代码示例

// 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'));