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 :)
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 :)
Share Improve this question asked Feb 26, 2014 at 14:30 Aleksander KorovinAleksander Korovin 3493 silver badges15 bronze badges 3- This is what happens when the first thing in your string is a separator. Can't you just ignore the first entry? – James Montagne Commented Feb 26, 2014 at 14:33
- 2 Have a look here, other people created proper JavaScript INI parsers already => stackoverflow./questions/3870019/… – Daniël Knippers Commented Feb 26, 2014 at 14:33
- possible duplicate of Javascript: string split returns an array with two elements instead of one – James Montagne Commented Feb 26, 2014 at 14:48
1 Answer
Reset to default 9To 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/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)