DEV Community

Cover image for How to Remove Extra Spaces from Text - 3 Ways (Including a 1-Click Fix)
TechMind
TechMind

Posted on

How to Remove Extra Spaces from Text - 3 Ways (Including a 1-Click Fix)

If you have ever scraped data, imported CSV files, or copy-pasted content from a PDF, you know the pain of extra spaces in strings.

// You expect this:
"Hello World. This is clean."

// You get this:
"Hello     World.   This  is  messy."
Enter fullscreen mode Exit fullscreen mode

It breaks string comparisons, corrupts database fields, and makes your content look unprofessional.

Why It Happens

Extra spaces come from:

  • PDF extraction — PDFs store characters with spacing metadata that leaks on extraction

  • HTML copy-paste —   and layout spaces copy over when grabbing web content

  • User input — double spacebar taps, especially on mobile
    Data migrations — moving between systems often introduces whitespace inconsistencies

3 Ways to Fix It

1. JavaScript (client-side)

const cleanText = text.replace(/  +/g, ' ').trim();
// Or more thorough:
const cleanText = text.replace(/\s\s+/g, ' ').trim();

Enter fullscreen mode Exit fullscreen mode

2. Python (data processing)

import re
clean = re.sub(r' +', ' ', raw_text).strip()
Enter fullscreen mode Exit fullscreen mode

3. Quick Manual Fix (no code)

For non-technical users or quick one-off cleaning, TechMind.click has a free Remove Spaces tool. Paste text → click button → copy clean result. No login, no limit.

When to Use Which

Scenario

  1. Production code / data pipeline
  2. One-off content cleanup
  3. Non-technical team member needs it
  4. Large dataset automation

Best approach

  1. JS or Python regex
  2. TechMind.click online tool
  3. TechMind.click online tool
  4. Python with re module

Bonus: Other Useful Text Utilities

If you work with text data regularly, these are also worth bookmarking:

Case converters (UPPERCASE, lowercase, Title Case, Sentence case)
Slug generator for URLs
Reverse text
Image to PDF

TechMind.click has all of these in one place, free.

Have a better regex for handling non-breaking spaces and tabs too? Drop it in the comments.

Top comments (0)