/*
函数:格式化字符串
参数: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>"

最新文章

  1. 重温Servlet学习笔记--servletContext对象
  2. 【洛谷P2513】逆序对数列
  3. KVO的底层实现
  4. Gulp解决发布线上文件(CSS和JS)缓存问题
  5. 【转】【C#】C#重绘windows窗体标题栏和边框
  6. Java系列:关于Java中的桥接方法
  7. Oracle instr用法
  8. 分布式文件系统MooseFS安装步骤
  9. 重写equal要重写 hashCode的原因
  10. randn命令中randn(&#39;state&#39;)和randn(&#39;seed&#39;)的不同
  11. Day2:T1搜索 T2最小生成树
  12. ●POJ poj 2112 Optimal Milking
  13. ECharts, PHP, MySQL, Ajax, JQuery 实现前后端数据可视化
  14. 对Python这门课程的理解。
  15. [Python]range与xrange用法对比
  16. Java 读书笔记 (十五) Java 异常处理
  17. [转]Date and String Function in BluePrism
  18. Python--day08(文件操作)
  19. 微信开发创业交流QQ群列表
  20. 一次tomcat配置参数调优Jmeter压力测试记录前后对比

热门文章

  1. NodeList对象的特点
  2. luogu 3698 [CQOI2017]小Q的棋盘 树形dp
  3. E. Intergalaxy Trips
  4. 【BZOJ3098】 Hash Killer II
  5. python关闭socket端口立即释放
  6. Activity中使用PagerAdapter实现切换代码
  7. Content:&quot;\2715&quot;,特殊字符和图标
  8. iTerm2使用Profiles自动登录
  9. Celery分布式队列学习
  10. Activity的生命周期是谁调用的?