String split returns an array with two elements instead of one

后端 未结 12 1541
渐次进展
渐次进展 2020-12-03 06:15

I don\'t understand this behaviour:

var string = \'a,b,c,d,e:10.\';
var array = string.split (\'.\');

I expect this:

consol         


        
相关标签:
12条回答
  • 2020-12-03 07:09

    Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.

    0 讨论(0)
  • 2020-12-03 07:10

    This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.

    If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

    0 讨论(0)
  • 2020-12-03 07:11

    try this

    javascript gives two arrays by split function, then

    var Val = "abc@gmail.com";
    var mail = Val.split('@');
    
    if(mail[0] && mail[1])  {   alert('valid'); }
    else    {   alert('Enter valid email id');  valid=0;    }
    

    if both array contains length greater than 0 then condition will true

    0 讨论(0)
  • 2020-12-03 07:12

    A slightly easier version of @xdazz version for excluding empty strings (using ES6 arrow function):

    var array = string.split('.').filter(x => x);
    
    0 讨论(0)
  • 2020-12-03 07:17

    According to MDN web docs:

    Note: When the string is empty, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.

    const myString = '';
    const splits = myString.split();
    
    console.log(splits); 
    
    // ↪ [""]
    
    0 讨论(0)
  • 2020-12-03 07:20

    so; [String.prototype] split(separator, limit) return to the normal limit parameter is empty.

    "".split(",") // [""]
    
    "a,b,c.".split(".", 1) // ["a,b,c"]
    

    If you could not have done this too, without limit parameter. I think this is a normal operation...

    0 讨论(0)
提交回复
热议问题