JavaScript split gives array size one instead of zero for empty string

前端 未结 3 1543
礼貌的吻别
礼貌的吻别 2021-01-25 23:38

I want to split a string by comma to get an array in Node.js.

exports.test = function(rq, rs){

   var mailList = \"sharan@test.com,pradeep@test.com\";
   var ar         


        
相关标签:
3条回答
  • 2021-01-26 00:17

    Everything before the first match is returned as the first element. Even if the String is Empty. It's not null

    If you want split and return an 0 length Array, I recommand you to use the underscore.string module and the words method :

    _str.words("", ",");
    // => []
    
    _str.words("Foo", ",");
    // => [ 'Foo' ]
    
    0 讨论(0)
  • 2021-01-26 00:19

    One way to do is to check whether the first value of the split array is empty or not

    var arrayList = mailList.split(",");
    if(arrayList[0] != ""){
      arrayLength = arrayList.length;
    }else{
      arrayLength = 0;
    }
    
    0 讨论(0)
  • 2021-01-26 00:28

    The returned array contains a single empty string ([""]). It works this way because everything up until the first match (or end of string) is returned as the first element of the array. In the case of the empty string, this is an empty string.

    If you think about how an implementation of the split algorithm might look like, this makes sense. Probably you start with an empty string containing the current element, and then you loop through the letters of the string adding them to the current element until you get to the end of the string or a separator. Then you push the current element onto the results array.

    In the case where you have a zero length string, you start with an empty string for the current element. You directly reach the end, so you push the empty string to the results array an return it.

    This is also how it is supposed to work. From the ECMAScript Language Specification:

    If the this object is (or converts to) the empty String, the result depends on whether separator can match the empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, which is the empty String.

    And from Mozilla:

    When found, separator is removed from the string and the substrings are returned in an array. If separator is not found or is omitted, the array contains one element consisting of the entire string.

    Note: When the string is empty, split() returns an array containing one empty string, rather than an empty array.

    If you dislike the behavior, you can write your own version:

    //Return an empty array if string is empty.
    //Otherwise return the result of the ordinary split.
    split2 = (separator) => this == "" ? [] : this.split(separator);
    
    0 讨论(0)
提交回复
热议问题