Big McLargeHuge
Big McLargeHuge

Reputation: 16056

Text replacement in nested elements

I have an element on my page that looks something like this:

<div id="product-123">
    <h3>${Title}</h3>
    <div>
        ${Description}
    </div>
    <div>
        ${Price}
    </div>
</div>

I have a JSON object that looks like this:

var Product = {
    'Title': 'Potion of Stamina',
    'Description': 'Restores stamina greatly.',
    'Price': '$100.00'
}

I need to replace ${Title} with Product.Title, ${Description} with Product.Description, etc.

So far, I can match the replacement strings in the element:

$('#product-123').html().match(/\$\{\w*\}/g)
// returns ["${Title}", "${Description}", "${Price}"]

I can also replace the replacement strings with something simple:

$('#product-123').html().replace(/\$\{(\w*)\}/g, '$1')
// returns
//"<div id="product-123">
//    <h3>Title</h3>
//    <div>
//        Description
//    </div>
//    <div>
//        Price
//    </div>
//</div>"

But none of these work:

$('#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'])

Each just replaces the replacement strings with undefined.

What do I do?

Upvotes: 0

Views: 105

Answers (2)

Royi Namir
Royi Namir

Reputation: 148524

Just do this : (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);

enter image description here

Upvotes: 0

Christophe
Christophe

Reputation: 28114

$('#product-123').html().replace(/\$\{(\w*)\}/g, function($0,$1){return Product[$1];});

When you use the matches outside a string, you need to pass them as function arguments.

Upvotes: 2

Related Questions