-2

我需要使用正则表达式用我在 JSON 数组中拥有的数据替换所有,{}并且{}它需要区分大小写。

s的数量{}可能会因页面而异。

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>
4

2 回答 2

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>
于 2013-10-21T15:16:15.797 回答
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;
}
于 2013-10-21T15:22:31.923 回答