Explain Codes LogoExplain Codes Logo

Regex to replace multiple spaces with a single space

javascript
regex-patterns
string-manipulation
text-normalization
Nikita BarsukovbyNikita Barsukov·Mar 4, 2025
TLDR

Efficiently replace multiple spaces with a single space using regex / {2,}/g along with JavaScript's String.replace():

let text = "Text with excess spaces."; text = text.replace(/ {2,}/g, " ");

This / {2,}/g pattern targets sequences of two or more spaces ({2,}) and replaces them globally (g) with a single space, thereby streamlining spacing within your string.

Decoding the regex pattern

The regex pattern /\s\s+/g is comprehensive in reducing all whitespace characters to a single whitespace. Here, the metacharacter \s matches any whitespace character.

text = text.replace(/\s\s+/g, ' ');

Remember, if your text contains other whitespace characters, like tabs or line breaks, confining the replacement to spaces (/ {2,}/g) might not deliver the desired output. Patterns /\s\s+/g or /\s{2,}/g are better fitted for such situations.

Your weapon against all whitespaces

For a stricter check that handles all types of whitespace characters, including tabs and newlines, /\s+/g works well:

text = text.replace(/\s+/g, ' ');

This ensures all consecutive whitespace characters get replaced with one space. It's a perfect fit when you need text normalization.

Performance checks and optimizations

Regex performance differs based on the pattern. Hence, it's wise to run performance tests using tools like JSPerf, especially when speed matters. While / {2,}/g remains the go-to for replacing spaces, it's best to test using your data set.

Don't forget to trim the fat!

Trimming spaces at the start and end of your string is usually a good idea:

text = text.replace(/\s+/g, ' ').trim();

This ensures your labor doesn't go in vain, with your string starting or ending with unnecessary spaces. Keep it lean!

Remember the replace and reassign mantra!

Post replacement, remember to reassign the result to your variable, as .replace() returns a new string:

text = text.replace(/\s+/g, ' ');

If reassignment is skipped, your original string will remain intact because .replace() respects its elders and avoids tampering with the original string.

Tricky scenarios and their solutions

Non-breaking spaces: the uninvited guest

HTML content or encoded text can harbor non-breaking spaces ( ), which white space character \s does not catch. You need to handle them separately:

text = text.replace(/(?:\s| )+/g, ' '); // " ", consider yourself evicted!

Newlines: preserving the poets

For text that needs to preserve newlines (like code snippets or poetry), consider a regex that lets them be:

text = text.replace(/[^\S\r\n]+/g, ' '); // Keeping it poetic with intact newlines.

This leaves line breaks unscathed while collapsing extra spaces.

Old browsers: how to not forsake them

With older browsers not supporting certain regex features, tools like Babel can help translate your regex into compatible syntax. This ensures no browser gets left behind in the space-collapse mission.

The jQuery side of things

Working in a jQuery environment? Here's how you replace:

$('#element').text(function(_, text) { return text.replace(/\s+/g, ' '); });

It's like gently whispering to the element, "Hey buddy, could you please collate these spaces?"