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>"

 

posted @ 2019-06-08 23:56  希希大队长  阅读(1099)  评论(0编辑  收藏  举报