String split returns an array with two elements instead of one

后端 未结 12 1540
渐次进展
渐次进展 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 06:54

    Because your string is composed of 2 part :

    1 : a,b,c,d,e:10

    2 : empty

    If you try without the dot at the end :

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

    output is :

    ["a,b,c:10"]
    
    0 讨论(0)
  • 2020-12-03 06:56

    That's because the string ends with the . character - the second item of the array is empty.

    If the string won't contain . at all, you will have the desired one item array.

    The split() method works like this as far as I can explain in simple words:

    1. Look for the given string to split by in the given string. If not found, return one item array with the whole string.
    2. If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
    3. In case the given string starts with the string to split by, the first item of the result array will be empty.
    4. In case the given string ends with the string to split by, the last item of the result array will be empty.

    It's explained more technically here, it's pretty much the same for all browsers.

    0 讨论(0)
  • You could add a filter to exclude the empty string.

    var string = 'a,b,c,d,e:10.';
    var array = string.split ('.').filter(function(el) {return el.length != 0});
    
    0 讨论(0)
  • 2020-12-03 07:01

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split

    trim the trailing period first

    'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"
    

    then split the string

    var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');
    

    console.log (array.length); // 1

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

    You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.

    So, this behavior is normal. What did you want to achieve by using this string.split?

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

    Use String.split() method with Array.filter() method.

    var string = 'a,b,c,d,e:10.';
    var array = string.split ('.').filter(item => item);
    
    console.log(array); // [a,b,c,d,e:10]
    console.log (array.length); // 1

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