TexToolsAI

Strip Zero-Width and Hidden Unicode from LLM Output

By VeloForge Labs · · 7 min read

Quick answer: Zero-width characters are invisible Unicode code points such as U+200B, U+200C, U+200D and U+FEFF. Models and copy-paste can add them. Strip them with a regex before saving or comparing text, but keep U+200D inside emoji sequences. Also remove direction controls and Unicode tag characters (U+E0000 to U+E007F).

TL;DR: Some characters take up no space on screen but still sit in the string. They break string matching, they can carry hidden instructions to the next model, and a sanitizer leaves them alone. A small cleaning function, run before the Markdown step, handles it. Below is one that we ran.

What are hidden Unicode characters?

Unicode has many characters that print nothing. You cannot see them in a chat window or a code editor, but they count as characters in a string. The groups that matter for text from a language model:

  • Zero-width and soft characters: U+200B zero width space, U+2060 word joiner, U+FEFF zero width no-break space (also used as a byte order mark), and U+00AD soft hyphen.
  • Joiners: U+200C zero width non-joiner and U+200D zero width joiner. They have real jobs, so be careful (see below).
  • Direction marks and controls: U+200E, U+200F, U+202A to U+202E and U+2066 to U+2069. They change how text is ordered when it is displayed.
  • Tag characters: the block from U+E0000 to U+E007F. AWS describes these as characters first designed as invisible markers for language tags, and says they have emerged as a way to try prompt injection.

All of the characters above fall in the Unicode "Format" category (Cf). We checked this in Node.js: the pattern /\p{Cf}/u matched every one we tried.

Why should you care?

String matching fails silently. "pass​word" and "password" look the same on screen and are not equal. We ran the comparison: it returns false. A search index, a deduplication step or an allow-list check can all miss a match because of one invisible character.

Hidden instructions can ride along. AWS's article says language models can read, interpret and act on tag characters, while a person looking at the same text sees nothing. A document, web page or message that carries them can pass hidden instructions into your next prompt. This is one way untrusted input reaches a model. The OWASP Top 10 for LLM Applications covers what happens when you trust model output without checking it, and the same rule applies to what goes in.

Your sanitizer will not remove them. In a local test, we passed a string with U+200B through marked and then sanitize-html, the libraries TexToolsAI uses. The character was still there afterwards. The same was true for tag characters in sanitize-html. A sanitizer protects against script and unsafe URLs. Hidden characters are a different problem, so they need their own step. See Why Markdown is not safe by default for what the sanitizer does cover.

The easy way: strip all Cf characters

The shortest fix is one line:

const clean = text.replace(/\p{Cf}/gu, "");

The u flag is required. MDN states that \p{...} is only supported in Unicode-aware mode.

This works for plain English text, but it is too blunt. We ran it on two inputs:

  • The family emoji (man, woman, girl) is three emoji joined by two U+200D characters. Removing the joiners leaves three separate emoji.
  • The England flag is U+1F3F4 followed by tag characters and a cancel tag (U+E007F). AWS's article describes this sequence and warns that stripping tag characters can turn such flags into a plain black flag. Our blind removal left only the black flag.

Joiners also matter in some writing systems. We did not test this, so check it with your own languages before you strip them.

A safer cleaning function

This version removes tag characters, zero-width characters and direction controls. It keeps real emoji flag sequences. It leaves joiners alone unless you ask for them to go.

// Keep a complete flag sequence (black flag + tag letters + cancel tag); drop any other tag character.
const FLAG_OR_TAG = /\u{1F3F4}[\u{E0020}-\u{E007E}]+\u{E007F}|[\u{E0000}-\u{E007F}]/gu;
const ZERO_WIDTH = /[​⁠­]/g;
const DIRECTION = /[‎‏‪-‮⁦-⁩]/g;
const JOINERS = /[‌‍]/g;

export function cleanHidden(text, { stripJoiners = false } = {}) {
  let out = text
    .replace(FLAG_OR_TAG, (m) => (m.length > 2 ? m : ""))
    .replace(ZERO_WIDTH, "")
    .replace(DIRECTION, "");
  if (stripJoiners) out = out.replace(JOINERS, "");
  return out;
}

// For logging: list the hidden characters found, as code points.
export function findHidden(text) {
  return [...text]
    .filter((c) => /\p{Cf}/u.test(c))
    .map((c) => "U+" + c.codePointAt(0).toString(16).toUpperCase().padStart(4, "0"));
}

Here is what it did when we ran it:

  • A string with 21 hidden tag characters spelling a sentence after the visible text Summarize this. came back as exactly Summarize this., and findHidden listed all 21.
  • "pass​word" became "password" and now equals it.
  • The family emoji and the England flag came back unchanged.
  • With stripJoiners: true, the family emoji became three separate emoji, as expected.
  • Running the function twice gave the same result as running it once.

The tag characters are written in the test as String.fromCodePoint(0xE0000 + charCode) for each letter, which is how you build them in code, because you cannot paste them visibly.

No code needed? Paste your text into the free AI text cleaner. It does this cleaning in your browser and lists the hidden code points it finds.

Where to run it

Clean text at the edges, before anything depends on it:

  1. On input. Clean user messages and retrieved documents before they go into a prompt.
  2. On output. Clean the model's reply before you store it or compare it.
  3. Before Markdown conversion. Run cleanHidden first, then convert and sanitize. In our run, "Hello​ **world**" plus a hidden tag string came out as <p>Hello <strong>world</strong></p>.
const text = cleanHidden(modelReply);
const res = await fetch("https://texttoolsai.org/api/convert", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer " + process.env.TEXTOOLSAI_API_KEY,
  },
  body: JSON.stringify({ markdown: text }),
});
const { html } = await res.json();

Keep the API key on the server, as shown in Render user Markdown safely in Next.js. If you want to see the conversion step without a key, paste Markdown into the playground on the home page. The request and response format is in the API docs. For the image and link side of model output, read Render LLM Markdown output safely.

What this does not cover

  • It does not stop prompt injection written in normal, visible words. Treat all model input and output as untrusted.
  • It does not remove other look-alike tricks, such as letters from different alphabets that look the same. That is a separate problem.
  • We did not test every model or every chat tool, so we make no claim about which of them produce hidden characters on their own.

Checklist

  • Know that \p{Cf} needs the u flag.
  • Remove tag characters (U+E0000 to U+E007F), but keep complete emoji flag sequences.
  • Remove zero-width spaces, the word joiner, the byte order mark and soft hyphens.
  • Remove direction controls unless you really need right-to-left control marks.
  • Keep U+200C and U+200D unless you have tested your languages and emoji.
  • Clean input and output, before conversion and sanitizing.
  • Log what you removed with findHidden, so you can see attacks and bugs.

Frequently asked questions

Can I just remove all invisible characters with one regular expression?

You can remove the whole Cf category with /\p{Cf}/gu, but it also removes joiners used in emoji sequences and the tag characters inside some flag emoji. A targeted function that keeps those is a safer default.

Are zero-width characters dangerous by themselves?

Not as scripts. They cannot run code. The risks are broken string matching and, for tag characters, hidden text that language models can read while people cannot see it, which AWS describes as a prompt injection vector.

Does a sanitizer like sanitize-html remove them?

In our local test, no. sanitize-html and marked both left U+200B in place, and sanitize-html kept tag characters too. Clean the text in a separate step before you convert it.

Will stripping tag characters break emoji?

It can break flags for England, Scotland and Wales, which are built from tag characters. The function above keeps complete flag sequences and removes only stray tag characters.

Should I strip the byte order mark?

U+FEFF at the start of a file is often a byte order mark, and in the middle of a string it is a hidden character. For text that came from a model or a user message, removing it is normally safe.