Created
November 14, 2014 08:31
-
-
Save jefsnare/e27845f09c18c828b772 to your computer and use it in GitHub Desktop.
JavaScript sprintf function
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
/** | |
* string.jssprintf function which acts like sprintf. | |
* | |
* Example | |
* | |
* 'Buy {0} get {1}'.jssprintf(5, 'one free'); | |
* which results in; | |
* 'Buy 5 get one free'. | |
*/ | |
(function () { | |
'use strict'; | |
if (!String.prototype.jssprintf) { | |
String.prototype.jssprintf = function() { | |
var args = arguments; | |
return this.replace(/{(\d+)}/g, function(match, number) { | |
return args[number] !== undefined ? args[number] : match; | |
}); | |
}; | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment