Last active
August 29, 2015 13:58
-
-
Save dovideh/10138204 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Wanted to check out the example from Frontend Masters by David Crockford | |
var template = '<table border="{border}">' + // | |
'<tr><th>Last</th><td>{last}</td></tr>' + // Hold table format in var template | |
'<tr><th>First</th><td>{first}</td></tr>' + // | |
'</table>'; // | |
var data = { // values to be replaced with RegEx | |
first: "Carl", // | |
last: "Jose", // | |
border: "3" // must be string | |
}; // | |
if (typeof String.prototype.supplant !== 'function') { // if there's no supplan prototype in String object | |
String.prototype.supplant = function (o) { // define it | |
return this.replace(/{([^{}]*)}/g, // regex pattern to match to match "{abc}" | |
function (a, b) { // accept two params | |
var r = o[b]; // new var hold the index of object passed and matched | |
return typeof r === 'string' ? r : a; // return if r is string else return whatever value | |
}); | |
}; | |
} | |
mydiv.innerHTML = template.supplant(data); // write to div |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment