Forked from GianlucaGuarini/String.prototype.template.js
Created
October 5, 2016 09:23
-
-
Save osv/7e5ae5a8b6b57475123e2817b0f0c01e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 (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