Bluefire
Bluefire

Reputation: 14099

Remove "unnecessary" spaces

I would like to remove all the "unnecessary" spaces from a string. Specifically:

"a b c d" => "a b c d" // spaces between two words are left in
" a b c d " => "a b c d" // spaces not between two words are removed
"a  b c   d" => "a b c d" // as are duplicate spaces

Is there any regex out there that I can put into String.replace() to do this for me?

Upvotes: 0

Views: 410

Answers (5)

connexo
connexo

Reputation: 56720

This should work in ES 3 enabled browsers as well.

function deleteUnwantedWhitespace (searchstring) {
   searchstring = searchstring.trim().split(" ");
   var tempArray = [];
   for (var i = 0; i < searchstring.length; i++) {
      if (searchstring[i]) {
          tempArray.push(searchstring[i]);
      }
   }
   return tempArray.join(" ");
}

Edit: I just learned that String.prototype.trim is part of ES 5.1, so here's the polyfill:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Upvotes: 3

AmmarCSE
AmmarCSE

Reputation: 30557

Do it manually

var strArr = ["a b c d", " a b c d ", "a  b c   d"];

for (var i = 0; i < strArr.length; i++) {
  console.log(removeSpaces(strArr[i]));
}

function removeSpaces(str) {
  str = str.replace(/ +/g, ' ');
  str = str.trim();

  return str;
}

Upvotes: 1

Perfectly possible. The first regex replaces 1 or more \s characters with a single space. This includes spaces, tabs, and new-lines.

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

If you just want spaces, use

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

This is also more than 5x faster than using a Boolean filter.

Upvotes: 0

asdf
asdf

Reputation: 3067

Use split, filter and join. This will split the string, filter out the extra empty array entries then rejoin them with a space:

variable.split(" ").filter(Boolean).join(" ");

Upvotes: 3

Barmar
Barmar

Reputation: 780688

Use trim() to remove spaces at the ends of the strings, and regexp replacement to replace multiple spaces in the middle.

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

Upvotes: 5

Related Questions