A tiny string highlighter that keeps my tests from being flaky

Yo Kirupa folks, I’m wiring up some UI tests right now and I keep losing time on failures where the diff is basically “one extra space” or a line wrap that shifts, so I started using a little text formatter to make assertions more stable.

export function normalizeForAssert(input, {
  max = 120,
  highlight = "",
} = {}) {
  const text = String(input)
    .replace(/\r\n?/g, "\n")
    .replace(/[\t\f\v]+/g, " ")
    .replace(/\u00A0/g, " ")
    .replace(/[ \u200B]+/g, " ")
    .replace(/\s+\n/g, "\n")
    .trim();

  const truncated = text.length > max ? text.slice(0, max - 1) + "…" : text;

  if (!highlight) return truncated;

  const safe = highlight.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return truncated.replace(new RegExp(safe, "gi"), (m) => `⟦${m}⟧`);
}

Neat part is it makes the “real” content pop while smoothing out wrapping/whitespace noise, so failures feel deterministic instead of random when fonts or layout shift a bit.