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