Created
March 8, 2011 19:04
-
-
Save nakajima/860794 to your computer and use it in GitHub Desktop.
javascript string interpolation
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.interpolate = function(object) { | |
return this.replace(/#{([\w0-9]+)}/g, function(val, match) { | |
return object[match]; | |
}) | |
} | |
String.prototype.evilInterpolate = function() { | |
return this.replace(/#{([\w0-9]+)}/g, function(val, match) { | |
return eval(match); | |
}); | |
} | |
alert("#{foo} IS #{bar}".interpolate({ foo: 'JavaScript', bar: 'FUN' })); | |
var foo = "JavaScript"; | |
var bar = "FUN"; | |
alert("#{foo} IS #{bar}".evilInterpolate()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment