7

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
1
  • 2
    Write your own 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. Commented Sep 28, 2016 at 19:16

6 Answers 6

13

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
Sign up to request clarification or add additional context in comments.

3 Comments

But I still want 'p,q,r'.split(',').splice() to split into an array of 3 elements
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.
This really doesn't answer the question. As @mortensen asked in this comment that 'p,q,r'.split(',').splice() will return an empty array [].
5

const arr = ''.split(',').filter(Boolean);
console.log('result:', arr)

answered Jun 27, 2022 at 21:00

1 Comment

Clever, thanks!
2

try with this

 r=s?s.split(','):[];
answered Sep 28, 2016 at 19:18

2 Comments

I think you'd want the last s to be an empty array.
Then how did you have time to answer it?
0

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

Comments

0

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(','));

answered Apr 27, 2023 at 18:48

Comments

-2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.