The example in this article describes how JavaScript implements parsing the contents of INI files. Share it with everyone for your reference, the details are as follows:
.ini is the abbreviation of Initialization File, that is, initialization file. The ini file format is widely used in software configuration files.
INI files consist of sections, keys, values, and comments.
A JavaScript function is rewritten based on the node.js version of node-iniparser to parse the content of the INI file, pass in the INI format string, and return a json object.
function parseINIString(data){ var regex = { section: /^\s*\s*([^]*)\s*\]\s*$/, param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/, comment: /^\s*;.*$/ }; var value = {}; var lines = data.split(/\r\n|\r|\n/); var section = null; lines.forEach(function(line){ if(regex.comment.test(line)){ return; }else if(regex.param.test(line)){ var match = line.match(regex.param); if(section){ value[section][match[1]] = match[2]; }else{ value[match[1]] = match[2]; } }else if(regex.section.test(line)){ var match = line.match(regex.section); value[match[1]] = {}; section = match[1]; }else if(line.length == 0 && section){ section = null; }; }); return value; }
Test INI content:
Return result object: