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?
Pranesh Ravi
19.2k10 gold badges51 silver badges70 bronze badges
asked Sep 28, 2016 at 19:14
mortensen
1,2372 gold badges14 silver badges24 bronze badges
6 Answers 6
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('')
//[]
answered Sep 28, 2016 at 19:17
Bartłomiej Gładys
4,6151 gold badge17 silver badges25 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
mortensen
But I still want
'p,q,r'.split(',').splice() to split into an array of 3 elementsDave Newton
Would break if you actually had a non-empty string, though; this seems like a special case that would be more easily handled by just checking for an empty string.
Vibhu
This really doesn't answer the question. As @mortensen asked in this comment that
'p,q,r'.split(',').splice() will return an empty array [].const arr = ''.split(',').filter(Boolean);
console.log('result:', arr)
answered Jun 27, 2022 at 21:00
Dream Castle
971 silver badge4 bronze badges
1 Comment
rjcarr
Clever, thanks!
try with this
r=s?s.split(','):[];
answered Sep 28, 2016 at 19:18
user2314737
29.7k20 gold badges109 silver badges126 bronze badges
2 Comments
Dave Newton
I think you'd want the last
s to be an empty array.Dave Newton
Then how did you have time to answer it?
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 ,[]));
answered Sep 28, 2016 at 20:03
Redu
26.3k6 gold badges61 silver badges84 bronze badges
Comments
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(','));
Comments
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']
answered Sep 28, 2016 at 19:24
F.Igor
4,5401 gold badge25 silver badges31 bronze badges
Comments
lang-js
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.