Remove all multiple spaces in Javascript and replace with single space

JavascriptJqueryReplace

Javascript Problem Overview


How can I automatically replace all instances of multiple spaces, with a single space, in Javascript?

I've tried chaining some s.replace but this doesn't seem optimal.

I'm using jQuery as well, in case it's a builtin functionality.

Javascript Solutions


Solution 1 - Javascript

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space

Solution 2 - Javascript

There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:

str.replace( /\s\s+/g, ' ' )

See this question for a full discussion on this exact problem: https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space

Solution 3 - Javascript

you all forget about quantifier n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp

here best solution

str = str.replace(/\s{2,}/g, ' ');

Solution 4 - Javascript

You can also replace without a regular expression.

while(str.indexOf('  ')!=-1)str.replace('  ',' ');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavascriptJosiahView Answer on Stackoverflow
Solution 2 - JavascriptGreg ShacklesView Answer on Stackoverflow
Solution 3 - JavascriptredexpView Answer on Stackoverflow
Solution 4 - JavascriptkennebecView Answer on Stackoverflow