Forked from WebReflection/String.prototype.template.js
Last active
August 29, 2015 14:13
-
-
Save dvdsmpsn/1c3b9d24d73d619733b6 to your computer and use it in GitHub Desktop.
ES6 Template like strings in ES3 compatible syntax.
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
/** | |
* 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