Skip to content

Instantly share code, notes, and snippets.

@krmgns
Created February 18, 2015 16:02
Show Gist options
  • Select an option

  • Save krmgns/fad3983f39f5a5530943 to your computer and use it in GitHub Desktop.

Select an option

Save krmgns/fad3983f39f5a5530943 to your computer and use it in GitHub Desktop.
Simple string formatter with integer and float operators.
String.prototype.format = function() {
var string = this.toString();
if (arguments.length) {
var tokens = string.match(/%([sdf])/g) || [],
token, i = 0, replace;
while (token = tokens.shift()) {
replace = arguments[i++];
switch (token) {
case "%d":
string = string.replace(token, parseInt(replace, 10) || 0);
break;
case "%f":
string = string.replace(token, parseFloat(replace) || 0);
break;
default:
string = string.replace(token, replace);
}
}
}
return string;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment