实现说明
顶层就这几处状态: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'));