Skip to content

Instantly share code, notes, and snippets.

@bga
Forked from WebReflection/String.prototype.template.js
Last active August 29, 2015 14:11
Show Gist options
  • Save bga/7c8f39f69d29956399fe to your computer and use it in GitHub Desktop.
Save bga/7c8f39f69d29956399fe to your computer and use it in GitHub Desktop.
String.prototype.template = function (scopeEval) {
// Andrea Giammarchi - WTFPL License
var
re = /\$\{([\S\s]*?)\}/g,
evaluate = [],
i = 0,
m
;
while (m = re.exec(this)) {
evaluate.push(
this.slice(i, re.lastIndex - m[0].length),
scopeEval('(' + m[1] + ')')
);
i = re.lastIndex;
}
evaluate.push(this.slice(i));
// Function is needed to opt out from possible "use strict" directive
return evaluate.join("")
};
var name = "Andrea"
// es3
console.log("Hello ${ name }".template(function(s) { return eval(s) }) == "Hello Andrea")// es3
// es6
console.log("Hello ${ name }" == "Hello Andrea")
// es3 -> es6
// sed s/\.template\(function\(s\) \{ return eval\(s\) \}\)//g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment