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>'
Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.
Template literals are enclosed by backtick ( ` ) characters instead of double or single quotes. Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression} .
Backticks ( ` ) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier. Features: we can interpolate any kind of expression in the template literals.
Template strings are a powerful feature of modern JavaScript released in ES6. It lets us insert/interpolate variables and expressions into strings without needing to concatenate like in older versions of JavaScript. It allows us to create strings that are complex and contain dynamic elements.
You can use replace
with a callback :
var optionString = templateString.replace(/{(\w+)}/g, function(_,k){
return obj[k];
});
Demonstration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With