簡體   English   中英

用一個對象中的值搜索和替換一個對象中的標簽

[英]Search and replace tags in one object with the values in another object

我有兩個加載到頁面中的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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM