Forked from WebReflection/String.prototype.template.js
Last active
August 29, 2015 14:11
-
-
Save bga/7c8f39f69d29956399fe 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
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