Skip to content

Instantly share code, notes, and snippets.

@jlis
Created May 29, 2013 11:40
Show Gist options
  • Save jlis/5669677 to your computer and use it in GitHub Desktop.
Save jlis/5669677 to your computer and use it in GitHub Desktop.
Javascript format function to replace placeholders in a string with content
// usage:
// string.format({key: replacement})
//
// example:
// 'Hello {name}, how are you doing? I am doing {mood}.'.format({name: 'Mike', mood: 'fine'});
String.prototype.format = function() {
var formatted = this;
if (arguments.length && typeof arguments[0] == 'object') {
var vars = arguments[0];
for (v in vars) {
var regexp = new RegExp('\\{'+v+'\\}', 'gi');
formatted = formatted.replace(regexp, vars[v]);
}
}
return formatted;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment