Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dvdsmpsn/1c3b9d24d73d619733b6 to your computer and use it in GitHub Desktop.
Save dvdsmpsn/1c3b9d24d73d619733b6 to your computer and use it in GitHub Desktop.
ES6 Template like strings in ES3 compatible syntax.
/**
* Usage:
* 'Hello ${name}'.template({
* name: 'chaps'
* });
*
* From: https://gist.github.com/WebReflection/8f227532143e63649804
*/
String.prototype.template = function (object) {
// Andrea Giammarchi - WTFPL License
var
stringify = JSON.stringify,
re = /\$\{([\S\s]*?)\}/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