Created
April 16, 2011 20:56
-
-
Save christoomey/923494 to your computer and use it in GitHub Desktop.
Extend String prototype to include a subs method to interpolate a string
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
// From Douglas Crockford's http://javascript.crockford.com/remedial.html | |
// | |
// Usage: | |
// var person = { name: "James", age: 22 }; | |
// var template = "Hello {name}, how does it feel to be {age}?"; | |
// var personalGreeting = template.subs(person); | |
// => "Hello James, how does it feel to be 22?" | |
if (!String.prototype.subs) { | |
String.prototype.subs = function (o) { | |
return this.replace(/{([^{}]*)}/g, | |
function (a, b) { | |
var r = o[b]; | |
return typeof r === 'string' || typeof r === 'number' ? r : a; | |
} | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment