首页 > 编程 > JavaScript > 正文

Json对象替换字符串占位符实现代码

2019-11-21 00:07:50
字体:
来源:转载
供稿:网友
例如:

  含有占位符的字符串hello,{name},your birthday is {birthday };
  提供的Json对象{name: "czonechan", birthday : "1989-07-02" } ;
  替换后为 hello,czonechan,your birthday is 1989-07-02。

实现代码:
复制代码 代码如下:

Object.prototype.jsonToString=function(str) {
o=this;
return str.replace(//{/w*/}/g, function (w) {
r = w.substr(1,w.length-2);//去除{}
return (o[r]===0)?0:(o[r] ? o[r] : "");//o[r]===0这句是为了实现当值为0时输出0而不是空。
});
};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表