When i try to parse by js split the first element is empty string

自古美人都是妖i 提交于 2019-12-12 18:14:52

问题


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(1) works:
Index 0: everything before the matching seperator
Index n: The nth result after the matching seperator until the next occurence of the matching seperator or endofstring.

Since there is nothing before your first match since your first match occurs right at the start of the string, your 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)



来源:https://stackoverflow.com/questions/22044461/when-i-try-to-parse-by-js-split-the-first-element-is-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!