Skip to content

Instantly share code, notes, and snippets.

@rahulsivalenka
Last active June 14, 2016 19:26
Show Gist options
  • Save rahulsivalenka/1ff811787006ee75e815 to your computer and use it in GitHub Desktop.
Save rahulsivalenka/1ff811787006ee75e815 to your computer and use it in GitHub Desktop.
Adding a String format function similar to C's printf to the String prototype and String object
// implementation of format function on the String prototype
// this is similar to printf() in C
// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
// adding a method to String
if (!String.format) {
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
;
});
};
}

String format function

Similar to C's printf()

Usage

Using prototype format function

"I'm the god damn {0}{1}".format("Batman", "!");
// returns I'm the god damn Batman!

Using String's format function

String.format("And I can call my god damn {0} whetever I {1} {2}", "car", "want");
// returns And I can call my god damn car whetever I want {2}

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment