May 15, 2010

supplant function

var template = '<table border="{border}">' +
    '<tr><th>Last</th><td>{last}</td></tr>' +
    '<tr><th>First</th><td>{first}</td></tr>' +
    '</table>';
    

var data = { first: "Carl", last: "Hollywood", border: 2 };

mydiv.innerHTML = template.supplant(data);

if (typeof String.proptotype.supplant !== 'function')
{
     String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g, 
                function(a, b) {
                  //a is $0, b is $1 (match 1)
                   var r = o[b];
                   return typeof r === 'string' ? r : a;
                });
    };
}