Really Simple JavaScript toTitleCase() Implementation

This function is not very much efficient, but it does what I needed it to, and will
probably be sufficient for your needs almost all 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 capitalized) 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.

Popular Posts