我需要使用正则表达式将{}
和{}
本身替换为JSON数组中的数据,并且需要区分大小写。
{}
的数量可能会因页面而异。
s ="<address><div>{Name}</div><div>{Address1}</div><div>{Address2}</div><div>{ZipCode} {City}</div><div>{State}</div><div>{Country}</div><div>{ContactName}</div></address>"
"DeliveryAddress":
{
"Id":5637169131,
"Name":"some name",
"Name2":null,
"Address":"Somewhere street 12",
"Address2":null,
"City":"Heven",
"ZipCode":"1111",
"State":"FL",
"Country":"US",
"VatNo":null,
"ContactRecId":"Receiving Department",
"ContactName":null,
"ContactPhone":null,
"ContactEmail":null,
"DefaultShopDeliveryAddress":false,
"DefaultServiceDeliveryAddress":false,
"IsOneTime":false,
"CaptureId":"00000000-0000-0000-0000-000000000000"
},
完成后我需要在我的json数组中使用匹配元素替换匹配的{tag}
示例
<address><div>some name</div><div>Somewhere street 12</div><div></div><div>1111 Heaven</div><div>FL</div><div>US</div><div></div></address>
答案 0 :(得分:1)
您可以使用此代码:
s ="<address><div>{Name}</div><div>{Address1}</div><div>{Address2}</div><div>{ZipCode} {City}</div><div>{State}</div><div>{Country}</div><div>{ContactName}</div></address>"
DeliveryAddress = {
"Id":5637169131,
"Name":"some name",
"Name2":null,
"Address1":"Somewhere street 12",
"Address2":null,
"City":"Heven",
"ZipCode":"1111",
"State":"FL",
"Country":"US",
"VatNo":null,
"ContactRecId":"Receiving Department",
"ContactName":null,
"ContactPhone":null,
"ContactEmail":null,
"DefaultShopDeliveryAddress":false,
"DefaultServiceDeliveryAddress":false,
"IsOneTime":false,
"CaptureId":"00000000-0000-0000-0000-000000000000"
};
for (var key in DeliveryAddress) {
var r = new RegExp('{' + key + '}', "i");
s = s.replace(r, DeliveryAddress[key]);
}
console.log(s);
<强>输出:强>
<address><div>some name</div><div>Somewhere street 12</div><div></div><div>1111 Heaven</div><div>FL</div><div>US</div><div></div></address>
答案 1 :(得分:0)
使用设置了全局和多行标志的String.replace:
function s_fill(s, dict) {
for (var n in dict) {
var re = new RegExp('{' + n + '}', 'gm');
s = s.replace(re, dict[n]);
}
return s;
}