Forked from WebReflection/String.prototype.template.js
Last active
January 7, 2021 13:47
-
-
Save GianlucaGuarini/672f63e275862ebcc5af 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