DEV Community

GoToolsOnline
GoToolsOnline

Posted on

The invisible characters breaking your string comparisons

You copy a value from a PDF or a web page, paste it into a form or a test, and a === b says false even though both strings look identical. Usually the culprit is a character you can't see.

The usual suspects

Character Code point Where it comes from
No-break space U+00A0 HTML  , Word, PDFs
Zero-width space U+200B CMS editors, chat apps, some websites to allow line breaks
Zero-width non-joiner / joiner U+200C / U+200D emoji sequences, some scripts
Byte order mark U+FEFF files saved as "UTF-8 with BOM", start of CSVs
Narrow no-break space U+202F macOS/iOS time formats, French typography

Finding them

const show = s => [...s].map(c => {
  const cp = c.codePointAt(0);
  return cp > 126 || cp < 32 ? `<U+${cp.toString(16).toUpperCase().padStart(4, '0')}>` : c;
}).join('');

show('price\u00A0100\u200B'); // "price<U+00A0>100<U+200B>"
Enter fullscreen mode Exit fullscreen mode

Cleaning them

const clean = s => s
  .replace(/[\u200B-\u200D\uFEFF]/g, '')      // zero-width + BOM: remove
  .replace(/[\u00A0\u2007\u202F]/g, ' ')       // no-break spaces: normal space
  .replace(/[ \t]+/g, ' ')                       // collapse runs
  .trim();
Enter fullscreen mode Exit fullscreen mode

Two cautions:

  • Don't strip U+200D blindly from user-facing text: it joins emoji like 👩‍💻 and matters in some languages. Removing it from IDs, emails and codes is fine.
  • String.prototype.trim() already removes U+00A0 and U+FEFF at the ends, but not U+200B, and it never touches the middle of the string.

Where this bites in practice

  • Email addresses pasted from a PDF failing validation.
  • CSV imports where the first column header is "\uFEFFid" instead of "id".
  • Duplicate-looking keys in a JSON object.
  • Search not matching because the stored value has a no-break space.

Normalising input at the boundary (form submit, CSV import) is cheaper than debugging it later.

Disclosure: I run GoToolsOnline. If you just need to clean a block of text by hand, its free whitespace cleaner lists the hidden characters it found and removes or converts them in the browser: https://gotoolsonline.com/tools/remove-spaces

Top comments (0)