Skip to content

Instantly share code, notes, and snippets.

@jefsnare
Created November 14, 2014 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jefsnare/e27845f09c18c828b772 to your computer and use it in GitHub Desktop.
Save jefsnare/e27845f09c18c828b772 to your computer and use it in GitHub Desktop.
JavaScript sprintf function
/**
* 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