Skip to content

Instantly share code, notes, and snippets.

@ovidiucs
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ovidiucs/10138204 to your computer and use it in GitHub Desktop.
Save ovidiucs/10138204 to your computer and use it in GitHub Desktop.
// 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