Created
July 20, 2014 12:50
-
-
Save ianchanning/dcb55d1685679e26e8c8 to your computer and use it in GitHub Desktop.
printf JavaScript
This file contains hidden or 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
if (!String.format) { | |
/** | |
* printf function | |
* @link http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format | |
* @example var fullName = String.format('{0} {1}', firstName, lastName); | |
* | |
* @param {string} format String with replacable parameters | |
* @returns {string} formatted string | |
*/ | |
String.format = function(format) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
return format.replace(/{(\d+)}/g, function(match, number) { | |
return typeof args[number] != 'undefined' ? args[number] : match; | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment