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?
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('')
//[]
'p,q,r'.split(',').splice() to split into an array of 3 elements'p,q,r'.split(',').splice() will return an empty array [].const arr = ''.split(',').filter(Boolean);
console.log('result:', arr)
try with this
r=s?s.split(','):[];
s to be an empty array.Using condition ? exprIfTrue : exprIfFalse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator
let text1 = ''
let text2 = '1,2,3,4,5,6,7,8'
console.log(text1 == '' ? [] : text1.split(','));
console.log(text2 == '' ? [] : text2.split(','));
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']
splitreplacement and break compatibility? If you split a non-empty string on','you get back an array with the original string in it, just like here.