Home >Web Front-end >JS Tutorial >JavaScript implements method of parsing the contents of INI files

JavaScript implements method of parsing the contents of INI files

高洛峰
高洛峰Original
2016-12-06 15:17:052497browse

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:

JavaScript implements method of parsing the contents of INI files

Return result object:

JavaScript implements method of parsing the contents of INI files


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn