最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Split empty string should return empty array - Stack Overflow

programmeradmin1浏览0评论

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
  • 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. – Dave Newton Commented Sep 28, 2016 at 19:16
Add a comment  | 

6 Answers 6

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

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']
发布评论

评论列表(0)

  1. 暂无评论