Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 206
mortensen Avatar asked Jul 14 '26 07:07

mortensen


1 Answers

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('')
//[]
like image 118
Bartłomiej Gładys Avatar answered Jul 16 '26 21:07

Bartłomiej Gładys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!