TDave00
TDave00

Reputation: 374

Search and replace tags in one object with the values in another object

I have two json files that I load into a page. One contains the name and value of the tag. The other json file contains the html. I've been stumped for a day googling and trying to replace these tags.

For example:

var tags = {
    title: "New Title",
    author: "John Doe"
};

var html = {
    header: "<div id=\"header\"><h1>{{title}}</h1</div>",
    content:  "<div id=\"content\"><h2>{{author}}</h2></div>"
};

I lifted this somewhere and I can replace my tags if the html is stored in a string, but I'm having problems getting this to work when the html is in an object.

var str = 'The Title is {{title}} and the author is {{author}}.  Proof it will replace multiple tags:  Again the author is {{author}}.';

var content = str.replace(/\{\{(.*?)\}\}/g, function(i, match) {
    return tags[match];
});

I need help iterating through all the values in the html object and replacing them with the correct tag values. Thanks

Upvotes: 0

Views: 41

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

You can iterate over each property in html object and replace its content

var tags = {
  title: "New Title",
  author: "John Doe"
};

var html = {
  header: "<div id=\"header\"><h1>{{title}}</h1</div>",
  content: "<div id=\"content\"><h2>{{author}}</h2></div>"
};

for (var key in html) {
  if (html.hasOwnProperty(key)) {
    html[key] = html[key].replace(/\{\{(.*?)\}\}/g, function(i, match) {
      return tags[match];
    });
  }
}


content.innerText = JSON.stringify(html, null, 2)
<pre id="content"></pre>

Upvotes: 1

Related Questions