我有两个加载到页面中的json文件。其中一个包含标签的名称和值。另一个json文件包含html。我已经迷迷糊糊了一天,试图替换这些标签。

例如:

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>"
};


我将其放在某个地方,并且如果html存储在字符串中,则可以替换我的标签,但是当html在对象中时,我无法使它起作用。

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];
});


我需要遍历html对象中的所有值并将其替换为正确的标记值的帮助。谢谢

最佳答案

您可以遍历html对象中的每个属性并替换其内容



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>

07-24 09:44
查看更多