Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript parser for a string which contains .ini data

If a string contains a .ini file data , How can I parse it in JavaScript ? Is there any JavaScript parser which will help in this regard?

here , typically string contains the content after reading a configuration file. (reading cannot be done through javascript , but somehow I gather .ini info in a string.)

like image 259
sat Avatar asked Oct 06 '10 06:10

sat


People also ask

Which direct method can be used to parse a string?

The querystring. parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL.

What is parsing a string in JavaScript?

parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

What is parser in JavaScript?

Parsing means analyzing and converting a program into an internal format that a runtime environment can actually run, for example the JavaScript engine inside browsers. The browser parses HTML into a DOM tree.


1 Answers

I wrote a javascript function inspirated by node-iniparser.js

function parseINIString(data){
    var regex = {
        section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
        param: /^\s*([^=]+?)\s*=\s*(.*?)\s*$/,
        comment: /^\s*;.*$/
    };
    var value = {};
    var lines = data.split(/[\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;
}

2017-05-10 updated: fix bug of keys contains spaces.

EDIT:

Sample of ini file read and parse

like image 107
cuixiping Avatar answered Sep 19 '22 04:09

cuixiping