zoukankan      html  css  js  c++  java
  • JS字符串格式化~欢迎来搂~~

    /*
        函数:格式化字符串
        参数:str:字符串模板; data:数据
        调用方式:formatString("api/values/{id}/{name}",{id:101,name:"test"});
                 formatString("api/values/{0}/{1}",101,"test");
      ****字符串中需要替换的数据用 {} 括起来,注意花括号里面不能有空格,data建议使用自定义对象,也就是python中的字典
    */ function formatString(str, data) { if (!str || data == undefined) { return str; } if (typeof data === "object") { for (var key in data) { if (data.hasOwnProperty(key)) { str = str.replace(new RegExp("{" + key + "}", "g"), data[key]); } } } else { var args = arguments, reg = new RegExp("{([0-" + (args.length - 1) + "])}", "g"); return str.replace(reg, function(match, index) { return args[index - (-1)]; }); } return str; }

    例子来了~

    text_str = "<tr>
                <th>{id}</th>
                <th>{name}</th>
                 <th>{author}</th>
                 <th>{publish}</th>
                </tr>"
     data = {"id":1,"name":"金瓶","author":"小强","publish":"西北出版社"};         
    new_str = formatString(str, data)
    
    ## new_str ===> "<tr>
                <th>1</th>
                <th>'金瓶'</th>
                <th>"小强"</th>
                 <th>"西北出版社"</th>
                </tr>"
  • 相关阅读:
    Live Writer配置
    protobufnet 学习手记
    好的Sql语句也能提高效率(二)
    关于CodeSmith的输出问题
    [Scrum]12.29
    [scrum] 1.4
    分享 关于c#注释的规范
    [Scrum] 1.3
    分享:将XML(VS提取注释时生成)转换为Chm的一个方法
    【Scrum】2010.12.27
  • 原文地址:https://www.cnblogs.com/dongxixi/p/10992238.html
Copyright © 2011-2022 走看看