Skip to content Skip to sidebar Skip to footer

Split Empty String Should Return Empty Array

If I use ''.split(',') I get [''] instead of an empty array []. How do I make sure that an empty string always returns me an empty array?

Solution 1:

Just do a simple check if the string is falsy before calling split:

function returnArr(str){
  return !str ? [] : str.split(',')
}

returnArr('1,2,3')
// ['1','2','3']returnArr('')
//[]

Solution 2:

try with this

r=s?s.split(','):[];

Solution 3:

I guess this should do it;

console.log(''.split(',').reduce((p,c) => c ? p.concat(c) : p ,[]));
console.log("test1,test2,".split(',').reduce((p,c) => c ? p.concat(c) : p ,[]));

Solution 4:

split() always splits into pieces (at least one) so you can try:

list=(!l)?[]:l.split(',');

Also you can write a new split method like:

String.prototype.split2 = function (ch) { 
   return (!this)?[]:this.split(ch) 
}

So tou can try:

''.split2(',');         //result: []
'p,q,r'.split2(',');    //result: ['p','q','r']

Post a Comment for "Split Empty String Should Return Empty Array"