Is there a built in way with jQuery to "title case" a string? So given something like bob smith, it turns into "Bob Smith"?


Solution 1:

You don't need jQuery for this; it can be accomplished using the native .replace() method:

function toTitleCase(str) {
    return str.replace(/(?:^|\s)\w/g, function(match) {
        return match.toUpperCase();
    });
}

alert(toTitleCase("foo bar baz")); // alerts "Foo Bar Baz"

Solution 2:

You can use css, like:

.className 
{
    text-transform:capitalize;
}

This capitalizes the first letter. You can read more here

Solution 3:

In jQuery 1.4+ (at least) you can use

var camelized = jQuery.camelCase("some-string");
// Returns "someString"

I could not find it when I last checked the documentation, but it's there and used internally.