HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Regex to replace multiple spaces with a single space

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
replacewithspacespacessinglemultipleregex

Problem

Given a string like:

"The dog has a long tail, and it is RED!"

What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?

Goal:

"The dog has a long tail, and it is RED!"

Solution

Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':

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


If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

string = string.replace(/  +/g, ' ');

Code Snippets

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

Context

Stack Overflow Q#1981349, score: 1415

Revisions (0)

No revisions yet.