Search code examples
javascriptsplit

split an empty string gives an element


why split on an empty string gives an element?

i.e. how to get 0 in the below case:

let tags = "";
let arr = tags.split(',');
console.log(arr.length);


Solution

  • You can simply remove the empty string elements form arr using filter

    let tags = "";
    let arr = tags.split(',').filter(x => x);
    console.log(arr.length);