Skip to content

Instantly share code, notes, and snippets.

@cybercase
Created August 20, 2014 10:23
Show Gist options
  • Save cybercase/2298e242e82d32b15787 to your computer and use it in GitHub Desktop.
Save cybercase/2298e242e82d32b15787 to your computer and use it in GitHub Desktop.
Python-like .format method for javascript String
// Original: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
// Edited: cybercase
if (!String.prototype.format) {
String.prototype.format = function(dict) {
return this.replace(/{(\w+)}/g, function(match, key) {
return typeof dict[key] !== 'undefined'
? dict[key]
: match
;
});
};
}
// example:
console.log('{salutation} {place}'.format({
salutation: 'hello',
place: 'world'})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment