Symbol.replace Customizes String Replacement

Implement Symbol.replace on a custom matcher object so String.prototype.replace runs literal token redaction without dynamic RegExp compilation.

JavascriptSecurity Boundaries

Code

snippet
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)}...`));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Inside the routine — Symbol.replace Customizes String Replacement

One way to read it: the class PrefixRedactor, doing all the work.

The core work runs in nested loops — outer while (cursor < input.length), inner while (end < input.length && /[A-Za-z0-9_-]/.test(input[end])).

Sequential operations below act directly upon module-level bindings: redactor, line.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The demo output is labeled (masked :, count :, custom :); each label names the call that printed it.

Key statements

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

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `redactor`, `line`.