Really Simple JavaScript toTitleCase() Implementation
- Categories:
- JavaScript
- Tags:
- javascript, titlecase, totitlecase
- Published:
- 9:46am on Friday 13th February, 2009
Googling for a quick answer to a problem I was having, I noticed today that there are no really simple solutions listed in the search results to a JavaScript implementation of toTitleCase() (the natural partner to the existing String methods toLowerCase() and toUpperCase().
So I made this one.
JavaScript TitleCase method
It’s not incredibly clever, but it does what I needed it to, and will probably be sufficient for your needs 90% of the time. The script extends the JavaScript String type with a new toTitleCase() method, which simply converts all the words in the string to their title-cased (i.e. the first letter is capitalised) equivalent. It effectively ignores words that are already upper-cased, and works fine with strings that include numbers.
String.prototype.toTitleCase = function () {
var A = this.split(' '), B = [];
for (var i = 0; A[i] !== undefined; i++) {
B[B.length] = A[i].substr(0, 1). »
toUpperCase() + A[i].substr(1);
}
return B.join(' ');
}
Include the above snippet in your script somewhere, and you can then call the method in the same way as the other String functions:
var s = "This is a sentence."; var t = s.toTitleCase();
Neat and simple, and sufficient for most of your JavaScript title-casing needs.

I'd love to hear what you think - please use the form below to leave your comments. Some HTML is permitted:
b,i,em,del,ins,strong,pre,code,blockquote,abbr. URLs or email addresses will be automatically converted into links.FatBusinessman at 1:31pm on 13th February, 2009 #
Matthew Pennell at 4:08pm on 13th February, 2009 #
Stephane Deschamps at 1:39pm on 19th February, 2009 #
Cachel at 6:13am on 28th February, 2009 #
Ryan Bateman at 1:59pm on 20th November, 2009 #