Skip to content

Instantly share code, notes, and snippets.

@victornpb
Created December 1, 2013 22:26
Show Gist options
  • Save victornpb/7741693 to your computer and use it in GitHub Desktop.
Save victornpb/7741693 to your computer and use it in GitHub Desktop.
format string "Hello {0}, {1}"
/** format string
* format("Hello {0}! {1}-{2}.", "World", "foo", "bar") --> "Hello World! foo-bar."
*/
function format(string, etc) {
var args = arguments;
return string.replace(/{(\d+)}/g, function(match, number) {
return typeof args[+number+1]!="undefined" ? args[+number+1] : match;
});
}
/** format string
* "Hello {0}! {1}-{2}.".format("World","foo","bar") --> "Hello World! foo-bar."
*/
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(bracket, n) {
return typeof args[+n]!="undefined"? args[+n] : bracket;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment