If the RegExp is defined global and I use the vals
array like I do, the result of exec will be the same everytime, so the code below is an infinity loop.
var regex = RegExp(/<(.*?)>.*?<\/\1>/, "g");
function readXml(xmlString) {
var obj = {};
var vals;
for (var i = 0;
(vals = regex.exec(xmlString)) !== null; i++) {
if (!obj[vals[1]]) obj[vals[1]] = [];
obj[vals[1]].push(readXml(vals[0].slice(vals[1].length + 1, -vals[1] - length - 3)));
}
if (i == 0) return xmlString;
return obj;
}
console.log(readXml("<a>a</a><b>b</b>"));
If the RegExp is defined in function, the result of exec will be the next match everytime, so the code below logs a and b.
function readXml(xmlString) {
var regex = RegExp(/<(.*?)>.*?<\/\1>/, "g");
var obj = {};
var vals;
for (var i = 0;
(vals = regex.exec(xmlString)) !== null; i++) {
if (!obj[vals[1]]) obj[vals[1]] = [];
obj[vals[1]].push(readXml(vals[0].slice(vals[1].length + 1, -vals[1] - length - 3)));
}
if (i == 0) return xmlString;
return obj;
}
console.log(readXml("<a>a</a><b>b</b>"));
If I do something else with vals
arrray in the loop, the result of exec will be the next match everytime, so the code below logs an empty object.
var regex = RegExp(/<(.*?)>.*?<\/\1>/, "g");
function readXml(xmlString) {
var obj = {};
var vals;
for (var i = 0;
(vals = regex.exec(xmlString)) !== null; i++) {
vals = [2]
}
if (i == 0) return xmlString;
return obj;
}
console.log(readXml("<a>a</a><b>b</b>"));
I think it should be an object with a and b in the first case too.
Why doesn't it just do the same thing in all cases?