Regex to find and remove extra whitespace

This pattern finds spaces and tabs at the start of a line, at the end of a line, and runs of two or more in the middle. It is a quick way to spot and clean up pasted or user-entered text.

The pattern

/^[ \t]+|[ \t]+$|[ \t]{2,}/gm

The tester opens with this pattern and the examples below already loaded. Nothing you type is uploaded.

How it works

^[ \t]+
Spaces or tabs at the start of a line.
[ \t]+$
Spaces or tabs at the end of a line.
[ \t]{2,}
Two or more spaces or tabs in a row inside a line.
|
Alternation: any of the three cases counts as a match.

Examples

Matches

Does not match

  • hello world
  • a b c
  • tidy

Use it in JavaScript

// Trim each line, then collapse inner runs to one space
const tidy = text
  .replace(/^[ \t]+|[ \t]+$/gm, '')
  .replace(/[ \t]{2,}/g, ' ');

// Remove every whitespace character, newlines included
const squashed = text.replace(/\s+/g, '');

Limits and tips

  • Replacing every match with nothing would join words that had a double space between them. To collapse those to one space, use the two-step code below.
  • To remove all whitespace including newlines use text.replace(/\s+/g, "").
  • JavaScript has str.trim() for the leading and trailing part, which is simpler than a regex when that is all you need.
  • \s also matches newlines and non-breaking spaces. This pattern uses [ \t] so that line breaks are preserved.

Frequently asked questions

How do I replace multiple spaces with one space?

Use text.replace(/[ \t]{2,}/g, " "). It turns any run of two or more spaces or tabs into a single space.

How do I remove leading and trailing spaces?

Use str.trim(), or text.replace(/^\s+|\s+$/g, "") if you want a regex.