Created
December 1, 2013 22:26
-
-
Save victornpb/7741693 to your computer and use it in GitHub Desktop.
format string "Hello {0}, {1}"
This file contains hidden or 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
/** 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