使用基于json Array的Regex在字符串中替换JavaScript

时间:2013-10-21 15:06:32

标签: javascript regex json

我需要使用正则表达式将{}{}本身替换为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>

2 个答案:

答案 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;
}