Home > Web Front-end > JS Tutorial > body text

JavaScript implements method of parsing the contents of INI files

高洛峰
Release: 2016-12-06 15:17:05
Original
2479 people have browsed it

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;
}
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!