Skip to content

Instantly share code, notes, and snippets.

@christoomey
Created April 16, 2011 20:56
Show Gist options
  • Save christoomey/923494 to your computer and use it in GitHub Desktop.
Save christoomey/923494 to your computer and use it in GitHub Desktop.
Extend String prototype to include a subs method to interpolate a string
// 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