The only thing I really hate about JavaScript is the requirement that you put conditions between parentheses.
Format.js
This small library implements the function known in other languages as format or (s)print(f).
It makes use of the amazingly powerful String.replace function. That function takes two arguments, the first of which is a regular expression, against which to test. The second can be a replacement string or a function, that receives as arguments the whole match and its various submatches, and that for each match in the string, if you are feeding String.replace a global regexp.
My format function is implemented in a mere 69 lines of code because of that. In its core, it basically is a single invocation of the replace method.
The definition I use for the directives is (how could it not be?) based on the GNUEmacs lisp format function. See the comments in the file for that. Besides that, Format.js comes with a function positionalFormat, which is so neat and small, that I can just show it right here:
function positionalFormat (str){
var args = arguments;
return str.replace(/{\s*(\d+)\s*}/g,
function(match, num){
return args[parseInt(num)+1]||match;
});
};
How to use? Well:
positionalFormat('argument { 1 } '
+ '(or is it { 2 }, or { 0 }?) '
+ 'comes { 1 }',
3, 'first', 1);
evaluates to: “argument first (or is it 1, or 3?) comes first”. Now ain’t that neat? See how you can reuse arguments?