← 中文资源

简体中文版本

用 Symbol.replace 定制字符串替换行为

在自定义匹配器对象上实现 Symbol.replace,让 String.prototype.replace 直接执行字面量脱敏替换,避开动态正则转义。

阅读英文原文

运行结果

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

masked : user=ada key=[MASKED:$&] next=[MASKED:$&] cost=$100
count  : 2
custom : user=ada key=tok_91... next=tok_zz... cost=$100

实现说明

逻辑集中在类 PrefixRedactor里。 核心工作在嵌套循环里完成:外层 while (cursor < input.length),内层 while (end < input.length && /[A-Za-z0-9_-]/.test(input[end]))。 各个操作都建立在顶层绑定之上:redactor、line。

使用要点

  • 不需要依赖清单;标准库就是全部。
  • 直接运行文件,输出会带上标签,比如 masked :、count :、custom :——输出的每一行都能指回产生它的那次调用。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件用顶层绑定保存自己的状态:redactor、line。

核心语句

result += input.slice(cursor, hit) + out;
result += input.slice(cursor);

代码示例

class PrefixRedactor {
  constructor(prefix) {
    this.prefix = prefix;
    this.lastMatchCount = 0;
  }

  // String.prototype.replace delegates directly to [Symbol.replace] when present
  [Symbol.replace](input, replacement) {
    let result = '';
    let cursor = 0;
    let count = 0;

    while (cursor < input.length) {
      const hit = input.indexOf(this.prefix, cursor);
      if (hit === -1) {
        result += input.slice(cursor);
        break;
      }
      let end = hit + this.prefix.length;
      while (end < input.length && /[A-Za-z0-9_-]/.test(input[end])) {
        end++;
      }
      const token = input.slice(hit, end);
      const out = typeof replacement === 'function'
        ? String(replacement(token, hit, input))
        : String(replacement);
      result += input.slice(cursor, hit) + out;
      cursor = end;
      count++;
    }
    this.lastMatchCount = count;
    return result;
  }
}

const redactor = new PrefixRedactor('tok_');
const line = 'user=ada key=tok_91ab_c next=tok_zz02 cost=$100';

// Unlike RegExp replacements, literal '$&' stays intact instead of expanding matched text
console.log('masked :', line.replace(redactor, '[MASKED:$&]'));
console.log('count  :', redactor.lastMatchCount);
console.log('custom :', line.replace(redactor, (tok) => `${tok.slice(0, 6)}...`));