First, John Gruber released his Title Case Perl script. Then Dan Benjamin issued a challenge to the Ruby community to do likewise, with prolific results. Finally, John asked for JavaScript implementations.
Not wanting to be left out of the fun, and having blatant disregard for my priorities at work, I came up with my own solutions. These are mostly straightforward ports of Gruber’s script — not very original or clever like some others, but they have the desired effect.
My first attempt is written in Python. It can be used as a module or from the command line. For example, to use as part of a larger program, you can import it:
from titlecase import titlecase
print titlecase('"Nothing to Be Afraid of?"')
Or you can read from STDIN:
$ python titlecase.py < examples-edge-cases
The latter example processes all lines in the file examples-edge-cases (taken from here) and prints the results to STDOUT.
Next, I wrote a JavaScript version. Usage is dead simple:
'"Nothing to Be Afraid of?"'.toTitleCase();
I only added the method to the String object’s prototype chain, which makes it not quite a flexible as some other implementations. For example, my method cannot be passed as a callback or mapping function.
One interesting note came about during the discussion of John Resig’s script: IE’s String.prototype.split method is broken. I got around that by building the tokenizer using regexp.exec instead. That’s the great thing about public discussions on these topics: I always come away from it learning a thing or two!
(BTW: check out this implementation by David Grouch. Short, sweet, very “JavaScript-esque”. And it handles more edge cases than any other implementation I’ve seen yet!)