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?
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?
Share Improve this question edited Sep 28, 2016 at 21:12 Pranesh Ravi 19.1k10 gold badges48 silver badges70 bronze badges asked Sep 28, 2016 at 19:14 mortensenmortensen 1,2372 gold badges14 silver badges23 bronze badges 1 |6 Answers
Reset to default 13Just 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('')
//[]
const arr = ''.split(',').filter(Boolean);
console.log('result:', arr)
try with this
r=s?s.split(','):[];
I guess this should do it;
console.log(''.split(',').reduce((p,c) => c ? p.concat(c) : p ,[]));
console.log("test1,test2,".split(',').reduce((p,c) => c ? p.concat(c) : p ,[]));
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']
split
replacement 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. – Dave Newton Commented Sep 28, 2016 at 19:16