Skip to content

Instantly share code, notes, and snippets.

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 osv/7e5ae5a8b6b57475123e2817b0f0c01e to your computer and use it in GitHub Desktop.
Save osv/7e5ae5a8b6b57475123e2817b0f0c01e to your computer and use it in GitHub Desktop.
String.prototype.template = function (object) {
// Andrea Giammarchi - WTFPL License
var
stringify = JSON.stringify,
re = /\$\{(.*?)\}/g,
evaluate = [],
i = 0,
m
;
while (m = re.exec(this)) {
evaluate.push(
stringify(this.slice(i, re.lastIndex - m[0].length)),
'(' + m[1] + ')'
);
i = re.lastIndex;
}
evaluate.push(stringify(this.slice(i)));
// Function is needed to opt out from possible "use strict" directive
return Function('with(this)return' + evaluate.join('+')).call(object);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment