У меня есть элемент на моей странице, который выглядит примерно так:
<div id="product-123">
<h3>${Title}</h3>
<div>
${Description}
</div>
<div>
${Price}
</div>
</div>
У меня есть объект JSON, который выглядит так:
var Product = {
'Title': 'Potion of Stamina',
'Description': 'Restores stamina greatly.',
'Price': '$100.00'
}
Мне нужно заменить $ {Title} на Product.Title, $ {Description} с Product.Description и т.д.
Пока что я могу сопоставить строки замены в элементе:
$('#product-123').html().match(/\$\{\w*\}/g)
// returns ["${Title}", "${Description}", "${Price}"]
Я также могу заменить заменяющие строки чем-то простым:
$('#product-123').html().replace(/\$\{(\w*)\}/g, '$1')
// returns
//"<div id="product-123">
// <h3>Title</h3>
// <div>
// Description
// </div>
// <div>
// Price
// </div>
//</div>"
Но ни одна из этих работ не работает:
$('#product-123').html().replace(/\$\{(\w*)\}/g, Product[$1])
$('#product-123').html().replace(/\$\{(\w*)\}/g, Product['$1'])
$('#product-123').html().replace(/\$\{(\w*)\}/g, '' + Product[$1])
$('#product-123').html().replace(/\$\{(\w*)\}/g, Product['/$1'])
Каждый просто заменяет заменяющие строки неопределенными.
Что я делаю?
$('#product-123').html().replace(/\$\{(\w*)\}/g, function($0,$1){return Product[$1];});
Когда вы используете совпадения за пределами строки, вам необходимо передать их как аргументы функции.
Просто сделайте следующее: (http://jsbin.com/EPEyAsa/3/edit)
if (!String.prototype.supplant) {
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
}
var Product = {
'Title': 'Potion of Stamina',
'Description': 'Restores stamina greatly.',
'Price': '$100.00'
}
var t= $("#t").clone().html().supplant(Product);
$("body").append(t);
$('#product-123').html(function(_, html){ return html.replace(/\$\{(\w*)\}/g, function($0,$1){ return Product[$1]; }); });