Replace multiple whitespaces with single whitespace in JavaScript string

Replace multiple whitespaces with single whitespace in JavaScript string

I have strings with extra whitespaces, each time there’s more than only one whitespace I’d like it be only one.
Anyone?
I tried searching google, but nothing worked for me.
Thanks

Solutions/Answers:

Solution 1:

Something like this:

var s = "  a  b     c  ";

console.log(
  s.replace(/\s+/g, ' ')
)

Solution 2:

You can augment String to implement these behaviors as methods, as in:

String.prototype.killWhiteSpace = function() {
    return this.replace(/\s/g, '');
};

String.prototype.reduceWhiteSpace = function() {
    return this.replace(/\s+/g, ' ');
};

This now enables you to use the following elegant forms to produce the strings you want:

"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra        whitespaces".reduceWhiteSpace();

Solution 3:

using a regular expression with the replace function does the trick:

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

Solution 4:

I presume you’re looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?

If that’s the case, you’ll need a regex like this:

mystring = mystring.replace(/(^\s+|\s+$)/g,' ');

This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:

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

Hope that helps.

Related:  Resize Google Maps marker icon image

Solution 5:

Here’s a non-regex solution (just for fun):

var s = ' a   b   word word. word, wordword word   ';

// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"

// or ES6:
s = s.split(' ').filter(n => n).join(' '); 
console.log(s); // "a b word word. word, wordword word"

It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.

Solution 6:

jQuery.trim() works well.

http://api.jquery.com/jQuery.trim/