Find and remove any double spaces in a JavaScript string?

rusty1_rusty1 asked this question 6 months ago
rusty1_rusty1 on Feb 10 · Edited

I need a function or method that takes a string and removes any double (or more) consecutive spaces in the string.

For example, a string like this:

"     An example string    with      lots   of spaces.    "

Should be converted into a new version with the unnecessary strings removed:

"An example string with lots of spaces."

How can I do that in JavaScript?

4 suggested answers
yaboy01 on Mar 13 · Edited

You can use a regular expression:

.replace(/\s+/g, " ")

As an example, here's how you could put it to use:

let string = "     An example string    with      lots   of spaces.    ";

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

// string = " An example string with lots of spaces. "

Notice that this replaces each instance of a double or more space and replaces it with a single space.

If you want to remove the leading and trailing space, you can add the trim() method.

0 replies
softwareguy411 on Mar 13 · Edited

Try this regular expression:

myString.replace(/ {2,}/g, " ");
0 replies
timmy123 on Mar 13

This will remove any multiple space instances and replace them with a single space:

string = string.replace(/ +(?= )/g, "");

That should do the trick for you :)

0 replies
nick on Mar 13
string.replace(/\s\s+/g, " ");
0 replies