Text & Writing Utilities • ⏱️ 5 min read

How to Clean and Format Messy Text: Extra Spaces, Empty Lines & HTML

Data sanitization techniques, removing non-breaking spaces, stripping HTML tags, trimming line breaks, and eliminating duplicate lines.

Why Copied Text Gets Messy

Every writer, programmer, and data analyst has experienced the frustration of copying text from a PDF, email client, or website, only to find the pasted result riddled with formatting errors: hard line breaks mid-sentence, double spaces between words, invisible non-breaking spaces ( ), or unwanted raw HTML markup.

Cleaning this text manually line-by-line is tedious and error-prone. Understanding text sanitization rules allows you to clean thousands of words in a single instant.

1. Collapsing Multiple Spaces into Single Spaces

Accidental double-spacing frequently creeps into manuscripts, particularly from older typing conventions where typists pressed the spacebar twice after periods:

  • Regex Pattern: /[ \t]+/g → ' '
  • This replaces any cluster of two or more adjacent spaces or tab stops with a single, clean space character.

2. Removing Unwanted Blank Lines & Line Breaks

PDF documents often insert a hard newline at the end of every visible line on the page, severing paragraphs into disconnected fragments:

  • Remove Empty Lines: /\n\s*\n/g → '\n' collapses consecutive blank lines into a single clean line break.
  • Trim Line Ends: Removes trailing spaces at the end of lines that can cause compilation warnings in programming environments.

3. Stripping Raw HTML Tags

When copying text from rich-text web editors into plain-text databases, residual HTML tags (like <p>, <span style="...">, or <strong>) clutter the content:

Regex Pattern: text.replace(/<[^>]*>/g, '')

This regular expression identifies any bracketed HTML tag and strips it away cleanly, leaving only the pure text content behind.

4. Eliminating Duplicate Lines (List Deduplication)

When compiling email lists, inventory SKUs, or keyword research sets, spreadsheets often contain duplicate rows. Deduplicating line-by-line involves splitting on newlines and filtering through a unique Set:

Unique Lines = Array.from(new Set(text.split('\n'))).join('\n')

This retains the first occurrence of every item while instantly stripping duplicate entries.

Clean and Format Text Instantly

Sanitize text, remove unwanted markup, and format data privately in your browser:

Put This Into Practice

Skip manual calculation math and compute your numbers in seconds with our free, 100% private Text Cleaner & Formatter.

Open Text Cleaner & Formatter →