Skip to content

Instantly share code, notes, and snippets.

@migimunz
Last active August 29, 2015 14:22
Show Gist options
  • Save migimunz/c50cdf3b93a37e105dff to your computer and use it in GitHub Desktop.
Save migimunz/c50cdf3b93a37e105dff to your computer and use it in GitHub Desktop.
A quick and dirty C#-like format function for js.
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