用js实现C#下的string.Format方法

之前的那个firefox下出问题,因为firefox的全局正则和IE不太一样这里改了一下

 

var str = "{0}aaa,b{{0}}bb,d{{a}}dd,c{{{0}}}cc{{0}},{{{{1},aaa,{1}}}}},ccc,{1}eee,{{1}},{{2}}\"ccc\""  
//var str = "{0} {1}:AAA:CCC"   
var data = ["tx{1}t1", "tx{{0}}t2"];  
str = StringFormat(str, data);  
alert(str);  

function StringFormat (str, list) {
    var data = list;
    var strArray = str.split("");
    for (var i = 0; i < data.length; i++) {
        var strReg = "(\\{+" + i + "\\}+)";
        var reg = new RegExp(strReg, "g");

        while (true) {
            var exec = reg.exec(str);
            if (null == exec)
                break;

            var start = exec[0].match(/{+/g);
            var end = exec[0].match(/}+/g);
            var findStr = exec[0].replace(/{{/g, "{").replace(/}}/g, "}");
            var lastIndex = exec.index + exec[0].length;

            for (var strIndex = exec.index; strIndex < lastIndex; strIndex++) {
                strArray[strIndex] = "";
            }

            if (start[0].length % 2 > 0 &&
                end[0].length % 2 > 0) {
                strArray[exec.index] = findStr.replace(/{\d+}/g, data[i]);
            }
            else {
                strArray[exec.index] = findStr;
            }
        }
    }

    str = strArray.join("");

    return str;
}


 

阅读更多
个人分类: 技术
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭