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?

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('')
//[]
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)

1 Comment

Clever, thanks!
2

try with this

  r=s?s.split(','):[];

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 ,[]));

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

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']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.