Last active
August 29, 2015 14:22
-
-
Save migimunz/c50cdf3b93a37e105dff to your computer and use it in GitHub Desktop.
A quick and dirty C#-like format function for js.
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
var format = function() { | |
var args = Array.prototype.slice.call(arguments); | |
var fmt = args[0]; | |
var vals = args.slice(1); | |
return fmt.replace(/(?:^|([^{]))\{(\d+)\}/g, function(_, pref, i) { | |
pref = pref || ''; | |
return pref + vals[i]; | |
}).replace(/{{|}}/g, function(s) { | |
return s[0]; | |
}); | |
}; | |
// {n} is replaced by the n-th argument | |
format("Hi, my name is {0}", "John"); | |
// => "Hi, my name is John" | |
format("Hello, {0} ({1}) {2}, nice to meet you.", "Brian", "Peter George St. John le Baptiste de la Salle", "Eno"); | |
// => "Hello, Brian (Peter George St. John le Baptiste de la Salle) Eno, nice to meet you." | |
// Supports escaping as well | |
format("format() replaces all instances of {{n}} with the n-th argument"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment