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
3 Answers
Reset to default 22You 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)