0

I have a search like function that takes in a string. I convert this string to array. The string has comma to distinct between two words.

Ideal format:
search-term-entered = xyz, abc, eee, fff

Now if the user follows my format, I can use split and get my array but what if:

search-term-entered = abc, xyz, , ,,, eee
or search-term-entered = , ,, abc, xyz,eee,fff
or something along these lines

If the user uses some other formatting, how do I get rid of extra white spaces? The only thing is can think of is looping through the array and checking whether for white spaces and removing it. Is there an easier method or way?

This is what my getArray looks like
getArray = search-term-entered.split(", ");

user3762742
  • 97
  • 2
  • 9
  • Possible duplicate of [how to remove null, undefined, NaN, 0s, falses and empty string from an array in JavaScript?](http://stackoverflow.com/questions/36076104/how-to-remove-null-undefined-nan-0s-falses-and-empty-string-from-an-array-in) –  Aug 18 '16 at 10:50
  • It's almost a duplicate, but I'd argue the extra requirement to trim the array terms warrants a new question – Joe Aug 18 '16 at 10:53
  • Is spaces between terms like (`abc xyz, abc`) valid ? – Pugazh Aug 18 '16 at 10:54
  • @Pugazh Yeah, I would like to treat them as 1 single string – user3762742 Aug 18 '16 at 10:55
  • Sidenote, don't split on `", "` (including the space). Split on the comma alone. – Yoshi Aug 18 '16 at 10:56

5 Answers5

3

As noted by @RC, you can find examples of how to filter out null / empty strings on this site already. But to also trim the white space you could use the following.

var s = ', ,, abc, xyz,eee,fff'; 
getArray = s.split(",").map(s => s.trim()).filter(s => s); 
Joe
  • 1,847
  • 2
  • 17
  • 26
2

Simple solution using String.match function:

var str = ', ,, abc, xyz,eee,fff',
    converted = str.match(/\b\w+?\b/g);

console.log(converted);  // ["abc", "xyz", "eee", "fff"]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

Something like this.

var str = ', ,, abc, xyz,eee,fff';

function GetFilteredArr(_str) {
  var arr = [];
  var temp = _str.split(',');
  temp.filter(function(v) {
    var _v = v.trim();
    if (_v == "")
      return false;
    arr.push(_v);
  });
  return arr;
}

var filterdArr = GetFilteredArr(str);

console.log(filterdArr);
Pugazh
  • 9,453
  • 5
  • 33
  • 54
0

Another one :P

", ,, abc, xyz,eee,fff".replace(/[, ]+/g, " ").trim().split(" ")
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
0

One other way might be

var s = "abc, xyz, , ,,, eee",
    a = s.replace(/(\s*,\s*)+/g,",").split(",");
console.log(a);
Redu
  • 25,060
  • 6
  • 56
  • 76