Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace keys in template string with object properties

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

like image 858
Muhammad Raheel Avatar asked Aug 11 '14 09:08

Muhammad Raheel


People also ask

Can object keys be strings?

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.

How do you use template literals in an object?

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} .

How to use backtick in JavaScript?

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.

What is a template string?

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.


1 Answers

You can use replace with a callback :

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

Demonstration

like image 95
Denys Séguret Avatar answered Nov 15 '22 00:11

Denys Séguret