When i try to parse by js split the first element

2019-07-22 02:22发布

问题:

I try to parse ini file, the first string is empty string, but others okay:

Structure:

[sensor1]
 param1: value

[sensor2]
 param1 : value
 param2 : value

And my code is:

 success: function(data) {
        var parsedArr = data.split(/\s*\[(.*)\]\s*\n/);
        console.log(parsedArr);
    }

Result:

 0: ""
 1: "sensor1"
 2: "name:      brightness temperature↵
 3: "sensor2"
 4: "name:      brightness temp. IR↵device:     HATPRO↵group:
 length: 5

Is it okay? And how to solve it?

Thanks in advance :)

回答1:

To remove the empty result at index 0:

var array = 'abcdef'.split('a');
array.shift() // Removes first element from array.

How split() works:
Index 0: everything before the matching seperator
Index 1: The first result matching the given seperator
Index 2: and so on.

Since there is nothing before your first match but an empty string, the first element in your array is an empty string :).

For a detailed documentation about split() take a look at the Mozilla-Docs: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)