mortensen mortensen - 2 months ago 13
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

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('')
//[]
Comments