简体   繁体   中英

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM