61

How can I remove all extra space between words in a string literal?

"some    value"

Should become

"some value"

Also,

"    This    should  become   something          else   too . "

Becomes

"This should become something else too ."

Do not worry about moving the .. Just as above is fine. I know I can use $.trim(str) to achieve the trailing/ending space removal. But, I'm not sure how to do the 1 space between words trick.

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348

8 Answers8

109
var string = "    This    should  become   something          else   too . ";
string = string.replace(/\s+/g, " ");

This code replaces a consecutive set of whitespace characters (\s+) by a single white space. Note that a white-space character also includes tab and newlines. Replace \s by a space if you only want to replace spaces.

If you also want to remove the whitespace at the beginning and end, include:

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

This line removes all white-space characters at the beginning (^) and end ($). The g at the end of the RegExp means: global, ie match and replace all occurences.

Rob W
  • 341,306
  • 83
  • 791
  • 678
22
var str = "    This    should  become   something          else   too . ";
str = str.replace(/ +(?= )/g,'');

Here's a working fiddle.

James Hill
  • 60,353
  • 20
  • 145
  • 161
  • 3
    A little explanation on the regex used would be nice! – Hari Pachuveetil Oct 03 '11 at 13:55
  • Why such a complicated reg exp when all that is needed is `\s+`? And [why lookaheads are not good](http://stackoverflow.com/questions/1843459/javascript-the-good-parts-why-is-lookahead-not-good). – epascarello Oct 03 '11 at 14:04
  • 1
    it means you are replacing one or more space characters `/ +` - that precede a space character `(?= )` throughout the whole string `/g` with nothing `,''` . You can read more about it [here](http://www.w3schools.com/jsref/jsref_regexp_nfollow.asp) – mogoman Oct 03 '11 at 14:06
  • ' Hello world '.replace(/\s+/g, " ").trim(); – Shiala Sep 16 '14 at 16:49
  • 1
    @Shiala, as with all things in programming, there are multiples ways to accomplish a goal (btw, this question was answered in 2011). If you would like to contribute a better answer, do it in an answer, not a comment. – James Hill Sep 16 '14 at 17:29
  • @JamesHill this was actually a comment since the code given in the answer wouldn't remove the first and last space in the string the .trim method was needed to complete the solution, now maybe putting in a line of code without an explanation wasn't the right way to go about it, I guess my comment should have said 'You should probably add the .trim method after removing the extra spaces' or maybe I shouldn't have commented anything, but that would be putting in way too mush work for a stranger that has never done anything in his life to help me so why do it? – Shiala Nov 19 '14 at 19:18
10

In case we want to avoid the replace function with regex,

We can achieve same result by

str.split(' ').filter(s => s).join(' ')
// var str = "    This    should  become   something          else   too . ";
// result is "This should become something else too ."

First, split the original string with space, then we will have empty string and words in an array. Second, filter to remain only words, then join all words with a whitespace.

V-SHY
  • 3,925
  • 4
  • 31
  • 47
4
var str = "    This    should  become   something          else   too . "
$.trim(str).replace(/\s(?=\s)/g,'')

This uses lookahead to replace multiple spaces with a single space.

Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43
3

jsFiddle Example

"    This    should  become   something          else   too . ".replace(/[\s\t]+/g,' ');
Brian
  • 4,974
  • 2
  • 28
  • 30
2

Another (perhaps easier to understand) regexp replacement that will do the trick:

var input = /* whatever */;
input = input.replace(/ +/g, ' ');

The regexp matches one or more spaces, so the .replace() call replaces every single or repeated space with a single space.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0
var str = 'some    value';
str.replace(/\s\s+/g, ' ');
Ivan
  • 2,262
  • 1
  • 18
  • 16
0

For my case, I had to combine other answers and add the /m modifier for a multiline string, resulting in:

string.replace(/^[ \s\t]*| +(?= )/gm, '')

let string = `
    I  want
    all   the extra
    spaces removed.
^                    
`;

console.log(string.replace(/^[ \s\t]*| +(?= )/gm, ''))
Design.Garden
  • 3,607
  • 25
  • 21