Inferensys

Prompt

Invisible Whitespace Character Stripping Prompt

A practical prompt playbook for data pipeline engineers to strip zero-width spaces, non-breaking spaces, and other invisible characters from model outputs before they break downstream parsers.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the specific job, the ideal user, and the operational boundaries for the Invisible Whitespace Character Stripping Prompt.

This prompt is for data pipeline engineers and platform operators whose downstream parsers, tokenizers, or databases fail on model-generated text containing invisible Unicode characters. The job-to-be-done is sanitizing a raw string by removing or replacing zero-width spaces (U+200B), non-breaking spaces (U+00A0), zero-width non-joiners (U+200C), and other invisible code points that are visually absent but structurally destructive. The ideal user is integrating an LLM's output into a system with strict character whitelists—such as a SQL database, a CSV parser, a JSON serializer, or a search index—and needs a deterministic, auditable cleaning step before ingestion.

Use this prompt when your validation layer has already confirmed that the model's output is structurally valid (e.g., valid JSON or well-formed XML) but downstream processes still break due to invisible characters. It is appropriate when the cost of a false positive (removing a character that was intentionally present) is lower than the cost of a false negative (allowing a destructive character through). The prompt is designed to be run as a post-processing step in a data pipeline, not as a real-time user-facing filter. It expects a single string input and returns a cleaned string along with a structured audit log of what was removed, enabling traceability and debugging.

Do not use this prompt for strings that require preservation of intentional Unicode formatting, such as bidirectional text markers in Arabic or Hebrew, or zero-width joiners in emoji sequences and Indic scripts. For those cases, use the dedicated Zero-Width Character Detection and Removal Prompt, which includes context-aware preservation logic. This prompt is also not a substitute for proper UTF-8 validation; if the input may contain invalid byte sequences, pair it with the Malformed UTF-8 Sequence Repair Prompt first. After implementing, always run the provided eval checks against a golden dataset of known destructive and benign invisible characters to calibrate the removal threshold for your specific system.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Invisible Whitespace Character Stripping Prompt works, where it fails, and what you must have in place before relying on it in a production pipeline.

01

Good Fit: Post-Processing for Broken Parsers

Use when: A downstream JSON, CSV, or SQL parser rejects a structurally valid model output due to invisible characters like zero-width spaces (U+200B) or non-breaking spaces (U+00A0). Guardrail: Run this prompt as a targeted sanitization step after schema validation fails, not as a blanket pre-processor on all traffic.

02

Bad Fit: Preserving Intentional Formatting

Avoid when: The text contains intentional Unicode formatting, such as right-to-left marks in multilingual content, zero-width joiners in emoji sequences, or non-breaking spaces in French typography. Guardrail: Use a character-class-specific allowlist for known safe Unicode blocks before stripping. Never strip all non-ASCII characters blindly.

03

Required Input: A Known Character Inventory

What to watch: Stripping characters without knowing which ones are present leads to silent data corruption. Guardrail: The prompt must receive a pre-computed inventory of detected invisible characters (e.g., from a Python unicodedata scan) so it can reason about each one before removal. Never ask the model to guess which characters are invisible.

04

Operational Risk: Silent Homograph Attacks

What to watch: Zero-width characters can be used to craft homograph attacks where paypal.com and paypаl.com look identical to a human but differ to a parser. Guardrail: Log all stripped characters with their Unicode code points and positions. Trigger a security review alert if zero-width characters are detected in security-sensitive fields like URLs, identifiers, or code blocks.

05

Operational Risk: Tokenizer Drift in Downstream Models

What to watch: Stripping invisible whitespace can change token boundaries, causing a downstream model to interpret the text differently than the original output intended. Guardrail: If the sanitized output will be fed into another model, validate that the semantic meaning is preserved by comparing embeddings or running a semantic equivalence eval. Do not assume whitespace-only changes are semantically neutral.

06

Bad Fit: Real-Time Streaming Pipelines

Avoid when: You need to sanitize characters in a streaming response with sub-millisecond latency. Guardrail: LLM-based sanitization adds unacceptable latency for real-time streams. Use a deterministic, rule-based sanitizer (e.g., a regex or str.replace chain) in the hot path. Reserve this prompt for offline repair of failed batches.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for stripping invisible whitespace characters from model outputs, ready to copy and adapt with your own inputs and constraints.

This prompt template is designed to be dropped directly into your post-processing pipeline. It instructs the model to act as a sanitization filter, removing invisible whitespace characters that break downstream parsers, tokenizers, and comparison logic. The template uses square-bracket placeholders for all variable inputs, making it easy to integrate with your application's templating engine or prompt assembly layer.

text
You are a text sanitization filter. Your only job is to remove invisible whitespace characters from the provided text while preserving all visible content and standard whitespace.

INPUT TEXT:
[INPUT]

CHARACTERS TO REMOVE:
- Zero-width space (U+200B)
- Zero-width non-joiner (U+200C)
- Zero-width joiner (U+200D)
- Zero-width no-break space (U+FEFF, Byte Order Mark)
- Non-breaking space (U+00A0) — convert to standard space (U+0020)
- Soft hyphen (U+00AD)
- Left-to-right mark (U+200E)
- Right-to-left mark (U+200F)
- Line separator (U+2028)
- Paragraph separator (U+2029)
- Ogham space mark (U+1680)
- En quad (U+2000), Em quad (U+2001), En space (U+2002), Em space (U+2003), Three-per-em space (U+2004), Four-per-em space (U+2005), Six-per-em space (U+2006), Figure space (U+2007), Punctuation space (U+2008), Thin space (U+2009), Hair space (U+200A) — convert all to standard space (U+0020)
- Any other Unicode characters in the "Separator, Space" (Zs) category or "Format" (Cf) category that are invisible

CONSTRAINTS:
[CONSTRAINTS]

OUTPUT FORMAT:
Return a JSON object with the following structure:
{
  "cleaned_text": "<the sanitized text>",
  "removed_characters": [
    {"character": "<Unicode code point>", "name": "<character name>", "count": <number of occurrences removed>}
  ],
  "changes_made": <total number of character removals or replacements>
}

Do not include any text outside the JSON object. Do not wrap the JSON in markdown code fences.

To adapt this template, replace [INPUT] with the text you need to sanitize. The [CONSTRAINTS] placeholder should be filled with any additional rules specific to your use case—for example, preserving intentional zero-width joiners in emoji sequences, keeping non-breaking spaces in HTML contexts, or adding custom characters to the removal list. If you have no additional constraints, replace [CONSTRAINTS] with 'None. Apply the default removal rules exactly as specified.' The output schema is designed to give you both the cleaned text and an audit trail of what was removed, which is essential for debugging false positives in production pipelines. Before deploying, test this prompt against a golden dataset that includes known invisible characters and verify that the removed_characters array accurately reports each removal.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Invisible Whitespace Character Stripping Prompt. Validate each input before passing it to the model to prevent downstream parser failures.

PlaceholderPurposeExampleValidation Notes

[INPUT_TEXT]

The raw string containing invisible whitespace characters to be stripped

Hello\u200B World\u00A0!

Must be a non-null string. Check for encoding validity (UTF-8). Empty strings are allowed and should return empty.

[TARGET_WHITESPACE]

List of specific invisible characters or Unicode categories to target for removal

['U+200B', 'U+00A0', 'U+FEFF', 'U+200C', 'U+200D']

Must be an array of valid Unicode code points or category names. Validate against a known allowlist of invisible characters. Null means strip all known invisible whitespace.

[PRESERVATION_LIST]

Characters or sequences that must not be removed even if they match the target set

['U+200D'] for Zero-Width Joiner in emoji sequences

Must be an array of valid Unicode code points. Each entry must also appear in [TARGET_WHITESPACE] or be a subset of the default target set. Null means no exceptions.

[OUTPUT_FORMAT]

Desired format for the returned result

json

Must be one of: 'json', 'text'. If 'json', the model must return a valid JSON object with 'cleaned_text' and 'removed_characters' fields.

[CONTEXT]

Optional description of where the text originated to help the model distinguish intentional formatting from corruption

User-submitted form field from a web application

If provided, must be a non-empty string. Used to reduce false positives for intentional invisible formatting in specific contexts like HTML or rich text.

[STRIP_MODE]

Controls whether to remove all instances or only leading/trailing occurrences

all

Must be one of: 'all', 'leading_trailing'. 'leading_trailing' only strips target characters from the start and end of the string.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the invisible whitespace stripping prompt into a production data pipeline with validation, retries, and observability.

The Invisible Whitespace Character Stripping Prompt is designed to be a post-processing repair step, not a standalone application. It should sit between the model's raw output and any downstream parser, database, or API that rejects or misinterprets invisible Unicode characters. The typical integration point is inside a data pipeline function, an API gateway middleware, or a validation hook that fires after the primary model response is received but before the payload is serialized to JSON, inserted into a database, or passed to a tokenizer. The prompt expects a single string input—the potentially contaminated text—and returns a cleaned string plus a structured audit report of what was removed. This audit report is critical for production observability; without it, silent data corruption can go undetected for weeks.

To wire this into an application, wrap the prompt call in a function that accepts the raw string, calls the model with the prompt template and the input, parses the JSON response, and validates the output shape. The response schema should be strictly enforced: a cleaned_text field containing the sanitized string, and a removals array where each object has a character, unicode_codepoint, count, and positions field. After parsing, run a structural validator that confirms the cleaned_text length plus the total removed character count equals the original input length. If validation fails, retry once with a more explicit instruction in the prompt, such as "You must account for every character in the input." If the retry also fails, log the failure, attach the original and partially cleaned strings, and route to a dead-letter queue for manual inspection. Do not silently pass unvalidated output downstream.

For model choice, prefer a fast, cheap model for this task—GPT-3.5 Turbo, Claude Haiku, or a fine-tuned small open-weight model are sufficient. The task is mechanical, not semantic. Latency matters because this is a synchronous repair step in a pipeline. Set a strict timeout (e.g., 2 seconds) and a token limit appropriate to your input size. If the model call times out or exceeds the token limit, fall back to a deterministic regex-based cleaner that strips known zero-width characters (U+200B, U+200C, U+200D, U+FEFF, U+00A0, etc.) and logs a warning that the AI repair was bypassed. This hybrid approach—AI repair with a deterministic fallback—gives you the nuance of model-based detection for rare or novel invisible characters while maintaining pipeline reliability. Log every repair event, including the model used, latency, characters removed, and whether the fallback was triggered. This data will help you decide if the prompt is still necessary or if your upstream model has improved enough to retire this repair step.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the cleaned string returned by the Invisible Whitespace Character Stripping Prompt. Use this contract to build a post-processing validator before the output enters downstream parsers or databases.

Field or ElementType or FormatRequiredValidation Rule

cleaned_string

string

Must not contain any characters from the Unicode categories Zs (except U+0020), Zl, Zp, or Cf (except those explicitly preserved per [PRESERVATION_LIST]). Validate with regex: /[\u00AD\u061C\u200B-\u200F\u2028-\u202F\u205F\u2060\uFEFF]/g must return null.

removal_report

array of objects

Each object must have keys: 'character' (string, the removed char), 'unicode_codepoint' (string, U+XXXX format), 'count' (integer), 'positions' (array of integers). Validate schema with JSON Schema validator.

removal_report.character

string

Length must be exactly 1. Must be the actual removed character, not a description.

removal_report.unicode_codepoint

string

Must match the pattern /^U+[0-9A-F]{4,6}$/. Must be the correct codepoint for the reported character.

removal_report.count

integer

Must be >= 1. Must equal the length of the 'positions' array.

removal_report.positions

array of integers

Each integer must be >= 0. Array must be sorted in ascending order. Positions refer to the index in the original [INPUT_STRING] before cleaning.

original_length

integer

Must equal the length of the provided [INPUT_STRING]. Used for audit trail.

cleaned_length

integer

Must equal original_length minus the sum of all removal_report.count values. Must equal the length of cleaned_string.

PRACTICAL GUARDRAILS

Common Failure Modes

Invisible whitespace characters like zero-width spaces, non-breaking spaces, and soft hyphens can silently corrupt downstream parsers, databases, and comparison logic. These failures are hard to spot during manual review and often surface only in production. Here are the most common failure modes and how to guard against them.

01

Zero-Width Character Corruption in String Comparisons

What to watch: Zero-width spaces (U+200B), zero-width non-joiners (U+200C), and zero-width joiners (U+200D) embedded in model outputs cause string equality checks, database lookups, and deduplication logic to fail silently. Two visually identical strings are treated as different values. Guardrail: Add a pre-ingestion normalization step that strips all zero-width characters from model outputs before they enter any comparison or storage path. Log a warning with the count and type of characters removed for auditability.

02

Non-Breaking Space Breaking Tokenization and Parsing

What to watch: Non-breaking spaces (U+00A0) and narrow non-breaking spaces (U+202F) are treated as non-whitespace by most tokenizers, parsers, and CSV readers. This causes field splitting failures, unexpected token boundaries, and malformed data rows. Guardrail: Normalize NBSP characters to standard spaces (U+0020) before tokenization or parsing, but only when the output is destined for plain-text systems. Preserve NBSP in HTML or XML contexts where it carries semantic meaning. Use context-aware normalization rules.

03

Soft Hyphen Injection Corrupting Search and Display

What to watch: Soft hyphens (U+00AD) inserted by models cause search index mismatches, broken copy-paste behavior, and invisible rendering artifacts. Users searching for a term won't find it because the soft hyphen splits the token. Guardrail: Strip all soft hyphens unconditionally from model outputs before indexing or storage. Add a specific eval test case that verifies search recall on strings that originally contained soft hyphens. Never rely on visual inspection to catch these.

04

Homograph Attack Vectors via Lookalike Whitespace

What to watch: Malicious or accidental insertion of Unicode whitespace lookalikes—such as Mongolian vowel separators (U+180E) or word joiners (U+2060)—can create homograph confusion in identifiers, URLs, or security-sensitive fields. Guardrail: Implement a strict allowlist of permitted whitespace characters (space, tab, newline) for any output entering security-sensitive paths. Reject or flag any output containing characters from Unicode categories Cf (Format) or Zs (Space Separator) beyond the allowlist. Log the specific code points for incident response.

05

Intentional Formatting Removal Causing Data Loss

What to watch: Aggressive stripping of all invisible characters can remove legitimate Unicode joiners and variation selectors that are semantically meaningful—breaking emoji sequences, Arabic script ligatures, or Devanagari conjuncts. Guardrail: Differentiate between formatting characters that affect rendering (ZWJ, ZWNJ, variation selectors) and purely invisible characters that carry no semantic weight (zero-width space, word joiner). Use Unicode property-based rules rather than blanket code-point removal. Test against a golden set of locale-specific strings that require preserved joiners.

06

Silent Passthrough to Downstream Systems Without Audit Trail

What to watch: Invisible characters pass through the AI pipeline undetected and land in databases, logs, or user-facing surfaces. Weeks later, a parsing failure or data corruption incident occurs with no way to trace the root cause. Guardrail: Add a lightweight detection step that scans every model output for non-standard whitespace characters before release. Emit structured metadata (characters found, positions, counts) alongside the cleaned output. This creates an audit trail for debugging and prevents silent corruption from accumulating in downstream systems.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Invisible Whitespace Character Stripping Prompt before deploying it into a production pipeline. Each criterion targets a specific failure mode that causes parser breakage or data corruption.

CriterionPass StandardFailure SignalTest Method

Zero-Width Space Removal

All U+200B characters are removed from [INPUT_TEXT].

U+200B remains in [OUTPUT_TEXT]; downstream parser reports invisible character error.

Parse [OUTPUT_TEXT] with a Unicode-aware regex \u200B and assert zero matches.

Non-Breaking Space Normalization

All U+00A0 characters are converted to U+0020 in non-HTML contexts.

U+00A0 remains; tokenizer splits words incorrectly or comparison logic fails.

Diff [INPUT_TEXT] and [OUTPUT_TEXT] for U+00A0 instances; assert all are replaced by U+0020.

Intentional Whitespace Preservation

Standard spaces, tabs, and newlines are preserved exactly as in [INPUT_TEXT].

Legitimate indentation or word spacing is collapsed; code blocks or formatted text are corrupted.

Compare [INPUT_TEXT] and [OUTPUT_TEXT] character-by-character for U+0020, U+0009, U+000A; assert count and position match.

Zero-Width Joiner Retention

U+200D is retained when it appears between emoji or script characters requiring joining.

Emoji families or ligatures break; rendered text shows separated glyphs instead of combined forms.

Provide [INPUT_TEXT] containing an emoji sequence with ZWJ; assert U+200D is present in [OUTPUT_TEXT] at the same position.

BOM Removal

U+FEFF is removed when it appears as a Byte Order Mark at position 0.

Downstream parser interprets BOM as content; first field in CSV or JSON is corrupted.

Check if [OUTPUT_TEXT] starts with U+FEFF; assert false.

Audit Trail Completeness

[OUTPUT_AUDIT] lists every removed character with its Unicode codepoint, count, and original position.

[OUTPUT_AUDIT] is missing, empty, or omits a removed character.

Parse [OUTPUT_AUDIT] as JSON; assert it is an array with codepoint, count, and positions fields for each removal type.

No False-Positive Removal

No visible or semantically significant character is removed.

A letter, digit, punctuation mark, or intentional formatting character is missing from [OUTPUT_TEXT].

Calculate Levenshtein distance between [INPUT_TEXT] and [OUTPUT_TEXT]; assert it equals the total count of intentionally removed invisible characters from [OUTPUT_AUDIT].

Round-Trip Structural Integrity

[OUTPUT_TEXT] preserves the same structural boundaries as [INPUT_TEXT] (e.g., JSON keys, CSV fields, XML tags).

A parser that successfully processed [INPUT_TEXT] fails on [OUTPUT_TEXT] due to structural corruption.

Parse both [INPUT_TEXT] and [OUTPUT_TEXT] with the target format parser; assert both succeed and produce equivalent structural trees.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a simple character class list. Strip zero-width spaces (U+200B), zero-width non-joiners (U+200C), zero-width joiners (U+200D), and non-breaking spaces (U+00A0). Return the cleaned string and a count of removed characters.

code
Strip all invisible whitespace characters from [INPUT_TEXT]. Remove zero-width spaces, zero-width non-joiners, zero-width joiners, and non-breaking spaces. Return the cleaned text and a count of characters removed.

Watch for

  • Missing detection of less common invisible characters (soft hyphens, word joiners)
  • No distinction between intentional formatting and noise
  • Silent data loss without an audit trail
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.