Download Cheat sheet PDF 12 pages · syntax, editors, patterns, Unicode, performance, debugging
Blog

Replace multiple spaces with a single space

Cleaning up whitespace in user input or scraped text is a common need. Here's the one-liner.

The basic version

const normalized = text.replace(/\s+/g, " ").trim();

Collapses any run of whitespace (spaces, tabs, newlines) into a single space, then trims leading and trailing whitespace.

Preserve newlines, collapse only horizontal whitespace

const normalized = text.replace(/[ \t]+/g, " ");

Use this when you want to preserve paragraph structure but flatten weird tab/space sequences within lines.

Trim every line individually

const cleaned = text
  .split(\n)
  .map(line => line.trim().replace(/[ \t]+/g, " "))
  .join(\n);

Python

import re

normalized = re.sub(r"\s+", " ", text).strip()

Watch out for

Inside code or pre-formatted text: collapsing whitespace inside <pre> or code blocks destroys indentation. Apply only to plain text content.

Non-breaking spaces: \s in some flavors doesn't match U+00A0 (non-breaking space) or other Unicode whitespace like U+2009 (thin space). For full Unicode whitespace, use [\s\u00A0\u2000-\u200B\u202F\u205F\u3000]+ or set the Unicode flag in your regex flavor.

Zero-width characters: ZWSP, ZWJ, BOM — these are whitespace-like but won't be caught by \s. Often unwanted: text.replace(/[\u200B-\u200D\uFEFF]/g, "").


← Back to blog