Skip to content

Instantly share code, notes, and snippets.

@silicakes
Last active August 29, 2015 13:58
Show Gist options
  • Save silicakes/10270237 to your computer and use it in GitHub Desktop.
Save silicakes/10270237 to your computer and use it in GitHub Desktop.
// a string interpolator, extending the String object,
// returns a new string with the values in the curly braces replaced
// with the ones provided by a passed object.
String.prototype.interpolate = function(obj) {
var buf = this;
for(x in obj) {
var re = new RegExp("{"+x+"}","g");
buf = buf.replace("{"+x+"}", obj[x]);
}
return buf;
}
var str = "My name is {name}, and I'm {age} years old";
str.interpolate({name: "Michael", age: 27}); // "My name is Michael, and I'm 27 years old"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment