I am looking for an efficient way to generically extract data from a string using another string as a template. Pseudocode:
var mystring = \"NET,1:1,0,ipv4,192.1
One solution is at http://jsfiddle.net/CrossEye/Kxe6W/
var templatizedStringParser = function(myTemplate, myString) {
var names = [];
var parts = myTemplate.replace( /\[([^\]]+)]/g, function(str, name) {
names.push(name);
return "~";
}).split("~");
var parser = function(myString) {
var result = {};
remainder = myString;
var i, len, index;
for (i = 0, len = names.length; i < len; i++) {
remainder = remainder.substring(parts[i].length);
index = remainder.indexOf(parts[i + 1]);
result[names[i]] = remainder.substring(0, index);
remainder = remainder.substring(index);
}
result[names[names.length - 1]] = remainder;
return result;
};
return myString ? parser(myString) : parser;
};
You can use it like this
console.log(templatizedStringParser(myTemplate, myString));
or this:
var parser = templatizedStringParser(myTemplate);
console.log(parser(myString));
There is almost certainly some cruft in there as I did this in a hurry. The use of the "~" might not work for you. And there are likely other problems if you have boundary issues, but it might cover many cases.