mortensen mortensen - 1 year ago 81
Javascript Question

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 also returns an empty array?

Answer Source

You can use splice()

''.split(',').splice()
//[]

this example works for your problem:

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

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