Skip to content

PII Redactor — JavaScript source

Paste text and automatically detect and mask personal data — emails, phone numbers, IP addresses, SSNs, credit card numbers, and dates.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

/**
 * pii-redactor — PII detection & redaction (email, phone, IPs, SSN, cards, dates).
 *
 * Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * CosmoDev polyglot showcase port of the `pii-redactor` tool, ported from
 * src/lib/pii-redactor.ts (the canonical TypeScript implementation).
 *
 * Every regex candidate passes a structural validator (octet ranges, Luhn
 * checksum, month/day bounds, E.164 digit count) to keep false positives
 * low; overlapping candidates resolve by type priority, so unambiguous
 * types claim their span before the fuzzy phone pattern. Never throws.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

/** All PII types, in display order. */
export const PII_TYPES = ['email', 'phone', 'ipv4', 'ipv6', 'ssn', 'credit-card', 'date'];

/**
 * Luhn checksum. `digits` must be a non-empty string of 0-9 (any separators
 * make it invalid - strip them first). Returns false otherwise.
 */
export function isValidLuhn(digits) {
  if (!/^\d+$/.test(digits)) return false;
  let sum = 0;
  let double = false;
  for (let i = digits.length - 1; i >= 0; i--) {
    let d = digits.charCodeAt(i) - 48;
    if (double) {
      d *= 2;
      if (d > 9) d -= 9;
    }
    sum += d;
    double = !double;
  }
  return sum % 10 === 0;
}

// --- Per-type structural validators (regex candidates pass through these) ---

const isValidIpv4 = (c) => c.split('.').every((o) => Number(o) <= 255);

const isValidIpv6 = (c) => {
  if (!/[A-Fa-f0-9]/.test(c)) return false; // lone ":" carries no hex digits
  const groups = c.split(':');
  if (!groups.includes('')) return groups.length === 8 && groups.every((g) => /^[A-Fa-f0-9]{1,4}$/.test(g));
  const parts = c.split('::'); // compressed: at most one "::", sides hold < 8 groups
  if (parts.length > 2) return false;
  const left = parts[0] ? parts[0].split(':') : [];
  const right = parts[1] ? parts[1].split(':') : [];
  return left.length + right.length <= 7 && [...left, ...right].every((g) => /^[A-Fa-f0-9]{1,4}$/.test(g));
};

const isValidDate = (c) => {
  const [, , mm, dd] = /^(\d{4})-(\d{2})-(\d{2})$/.exec(c) ?? [];
  if (mm === undefined) return false;
  return mm >= '01' && mm <= '12' && dd >= '01' && dd <= '31'; // lexicographic works for 2-digit
};

const isValidPhone = (c) => {
  const digits = c.replace(/\D/g, '');
  if (digits.length < 7 || digits.length > 15) return false;
  // IP-shaped (already claimed by ipv4) and date-shaped spans are never phones.
  return !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(c) && !/^\d{4}-\d{2}-\d{2}$/.test(c);
};

const isValidCard = (c) => {
  const digits = c.replace(/\D/g, '');
  return digits.length >= 13 && digits.length <= 19 && isValidLuhn(digits);
};

// --- Detectors: a global candidate regex + an optional structural validator.
// Array order IS the overlap priority (index 0 claims spans first).

const DETECTORS = [
  { type: 'email', re: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g },
  { type: 'credit-card', re: /\d(?:[ -]?\d){11,}/g, validate: isValidCard },
  { type: 'ssn', re: /\b\d{3}-\d{2}-\d{4}\b/g },
  { type: 'ipv6', re: /(?<![:\w])[A-Fa-f0-9]{0,4}(?::[A-Fa-f0-9]{0,4}){1,7}(?![:\w])/g, validate: isValidIpv6 },
  { type: 'ipv4', re: /(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?!\.?\d)(?!\w)/g, validate: isValidIpv4 },
  { type: 'date', re: /(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/g, validate: isValidDate },
  { type: 'phone', re: /(?<![\d(])(?:\+\d{1,3}[ .-]?)?(?:\(\d{1,4}\)|\d{1,4})(?:[ .-]?\d{2,4}){1,4}(?!\d)/g, validate: isValidPhone },
];

/**
 * Detect personal data in `text`. Pass `types` to scan for a subset (the
 * per-type toggles); omit it to scan for everything. Returns matches in
 * document order, non-overlapping, with exact `start`/`end` indices.
 */
export function detectPii(text, types) {
  const source = text ?? '';
  const active = types ? new Set(types) : null;
  const candidates = [];
  for (const det of DETECTORS) {
    if (active && !active.has(det.type)) continue;
    const re = new RegExp(det.re.source, det.re.flags); // fresh lastIndex per scan
    for (let m = re.exec(source); m !== null; m = re.exec(source)) {
      if (m[0] === '') break; // zero-length safety
      if (!det.validate || det.validate(m[0])) {
        candidates.push({ type: det.type, start: m.index, end: m.index + m[0].length, original: m[0] });
      }
    }
  }
  candidates.sort((a, b) => DETECTORS.findIndex((d) => d.type === a.type) - DETECTORS.findIndex((d) => d.type === b.type) || a.start - b.start);
  const kept = [];
  for (const c of candidates) {
    if (!kept.some((k) => c.start < k.end && k.start < c.end)) kept.push(c);
  }
  return kept.sort((a, b) => a.start - b.start);
}

/**
 * Redact personal data from `text`, replacing every detected span with
 * `options.mask` (default `[REDACTED]`). Accepts the same `types` subset
 * as detectPii.
 */
export function redactPii(text, options) {
  const source = text ?? '';
  const mask = options?.mask ?? '[REDACTED]';
  const matches = detectPii(source, options?.types);
  let out = source;
  for (let i = matches.length - 1; i >= 0; i--) {
    const m = matches[i];
    out = out.slice(0, m.start) + mask + out.slice(m.end); // right-to-left keeps indices valid
  }
  return out;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →