Created
August 20, 2014 10:23
-
-
Save cybercase/2298e242e82d32b15787 to your computer and use it in GitHub Desktop.
Python-like .format method for javascript 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
// 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