最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace keys in template string with object properties - Stack Overflow

programmeradmin0浏览0评论

I have an object like this.

var obj = {Id:1,Rate:5,Price:200,Name:"History"}

And a template like this.

var templateString = '<option id="{Id}">{Name}</option>'

I want to replace the template values with object values. How can i do this. I am no expert of javascript regular expressions.

The desired output

var optionString = '<option id="1">History</option>'

Fiddle Sample

I have an object like this.

var obj = {Id:1,Rate:5,Price:200,Name:"History"}

And a template like this.

var templateString = '<option id="{Id}">{Name}</option>'

I want to replace the template values with object values. How can i do this. I am no expert of javascript regular expressions.

The desired output

var optionString = '<option id="1">History</option>'

Fiddle Sample

Share Improve this question edited Aug 11, 2014 at 9:46 Muhammad Raheel asked Aug 11, 2014 at 9:14 Muhammad RaheelMuhammad Raheel 19.9k7 gold badges68 silver badges106 bronze badges 3
  • Perhaps you're looking for handlebarsjs.com? – James Donnelly Commented Aug 11, 2014 at 9:17
  • 1 No i dont want to use handlebarsjs – Muhammad Raheel Commented Aug 11, 2014 at 9:28
  • 1 How was this voted "too broad" ? Seriously ? – Denys Séguret Commented Aug 11, 2014 at 9:44
Add a comment  | 

3 Answers 3

Reset to default 22

You can use replace with a callback :

var optionString = templateString.replace(/{(\w+)}/g, function(_,k){
      return obj[k];
});

Demonstration

Without using regex, this can be done by finding all the properties of the object using Object.keys and then replace each of them by it's value.

Try like this:

Object.keys(obj).forEach(key => {
  templateString = templateString.replace(`**${key}**`, `"${obj[key]}"`);
});

Just this will work for you if it has just one occurrence

var optionString = templateString.replace('{Id}',obj.Id).replace('{Name}',obj.Name)
发布评论

评论列表(0)

  1. 暂无评论