Regex to collapse multiple spaces

Use /[ \t]{2,}/g with find and replace. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

Before

Too    many   spaces→here  and    there.

After (replace with " ")

Too many spaces→here and there.

How the pattern works

PartMeaning
[ \t]A space or tab
{2,}Two or more in a row
→ " "Replaced with a single space

Code examples

JavaScript

const out = text.replace(/[ \t]{2,}/g, " ");

Python

import re

out = re.sub(r'[ \t]{2,}', r' ', text)

PHP

$out = preg_replace('/[ \t]{2,}/', ' ', $text);

Notes and limitations

Use \s{2,} instead to also collapse line breaks into spaces. The Remove Extra Spaces tool does both.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex to collapse multiple spaces?
/[ \t]{2,}/g — it is used with find and replace. See the table above for what each part does.
Does it work in Python and PHP?
Yes — the code examples above use the same pattern with re in Python and preg functions in PHP.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.