当前位置:编程学习 > JAVA >>

Javascript解析INI文件内容的函数

.ini 是Initialization File的缩写,即初始化文件,ini文件格式广泛用于软件的配置文件。

INI文件由节、键、值、注释组成。


根据node.js版本的node-iniparser改写了个Javascript函数来解析INI文件内容,传入INI格式的字符串,返回一个json object。


[javascript] 
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; 

    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;
    }
测试INI内容:

\


返回结果对象:

 \

补充:web前端 , JavaScript ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,