user3762742
user3762742

Reputation: 97

Best way to remove white spaces from a varied formatted string and convert it to array

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(", ");

Upvotes: 0

Views: 89

Answers (5)

Redu
Redu

Reputation: 26161

One other way might be

var s = "abc, xyz, , ,,, eee",
    a = s.replace(/(\s*,\s*)+/g,",").split(",");
console.log(a);

Upvotes: 0

sabithpocker
sabithpocker

Reputation: 15566

Another one :P

", ,, abc, xyz,eee,fff".replace(/[, ]+/g, " ").trim().split(" ")

Upvotes: 0

Pugazh
Pugazh

Reputation: 9561

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);

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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"]

Upvotes: 2

Joe
Joe

Reputation: 1885

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); 

Upvotes: 3

Related Questions