44
votes

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

13
FYI: camel case strings should not contain spaces.Wayne
What's the word then for capitalizing the first character in a word?AnApprentice
sentence case is what you're looking for, though knowing to capitalize proper nouns may be a big requirement.sarnold
— It sounds like you're describing "title case", where each word starts with a capital letter.Ben Blank
The title is misleading, please change it to "title case"emonik

13 Answers

74
votes

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"
49
votes

You can use css, like:

.className 
{
    text-transform:capitalize;
}

This capitalizes the first letter. You can read more here

20
votes

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.

8
votes

If you want to combat the terrible people in the world who TYPE IN ALL CAPS, and also title case it at the same time, you can use this variation of the top answer here:

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

alert(toTitleCase("FOO BAR baz")); // alerts "Foo Bar Baz"
4
votes

There isn't anything built-in to jQuery that does it, but you can checkout this site that has a basic code example:

http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/

String.prototype.toCamel = function(){
    return this.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
};

It would seem that from there you could call the code like so:

var str = "my string to camel case";
str = str.toCamel();
if ( typeof console !== 'undefined' ) console.log(str);
4
votes

is way more simple...
You have to use a callback in replace.

toCamelCase = function(str){
  return str.replace(/-\w/g,function(match){return match[1].toUpperCase()})
}
// this works for css properties with "-" 
// -webkit-user-select => WebkitUserSelect

You can change the RegExp to /[-\s]\w/g or /(^|[-\s])\w/g or other...

2
votes

I know this question is a bit old but,

Here's my version of camelCase function:

var camelCase = (function () {
    var DEFAULT_REGEX = /[-_]+(.)?/g;

    function toUpper(match, group1) {
        return group1 ? group1.toUpperCase() : '';
    }
    return function (str, delimiters) {
        return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
    };
})();

It handles all of the following edge cases:

  • takes care of both underscores and hyphens by default (configurable with second parameter)
  • string with unicode characters
  • string that ends with hyphens or underscore
  • string that has consecutive hyphens or underscores

Here's a link to live tests: http://jsfiddle.net/avKzf/2/

Here are results from tests:

  • input: "ab-cd-ef", result: "abCdEf"
  • input: "ab-cd-ef-", result: "abCdEf"
  • input: "ab-cd-ef--", result: "abCdEf"
  • input: "ab-cd--ef--", result: "abCdEf"
  • input: "--ab-cd--ef--", result: "AbCdEf"
  • input: "--ab-cd-__-ef--", result: "AbCdEf"

Notice that strings that start with delimiters will result in a uppercase letter at the beginning. If that is not what you would expect, you can always use lcfirst. Here's my lcfirst if you need it:

function lcfirst(str) {
    return str && str.charAt(0).toLowerCase() + str.substring(1);
}
1
votes
    function camelCase(str){
        str     = $.camelCase(str.replace(/[_ ]/g, '-')).replace(/-/g, '');
        return  str;//.substring(0,1).toUpperCase()+str.substring(1);
    },
1
votes

Use inbuilt camelcase method in jquery:

$.camelCase($("#text").html());
1
votes

You can also implement a pure javascript extension method like this:

String.prototype.capitalize = function () {

    return this.toLowerCase().replace(/\b[a-z]/g, function (letter) {
        return letter.toUpperCase();
    });
};

And call it like this:

"HELLO world".capitalize()
0
votes
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {


   $('.clsToTitleCase').keyup(function () { 

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

    });
})
</script>

<body>

<input class='clsToTitleCase' type='text'>
</body>
</html>
0
votes

You can also use method like this -

toTitleCase: function (str) {
        return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
    }
0
votes

I have modified rBizzle's code slightly. I don't want to mess with the McClouds and McIntosh's of the world (I'm listening to Celtic music right now!), so I added a condition to only modify if ALL CAPS or ALL lowercase:

function isUpperCase(str) {
    return str === str.toUpperCase();
}

function isLowerCase(str) {
    return str === str.toLowerCase();
}

function toProperCase(str) {
	//only mess with it if it is all lower or upper case letters
	if (isUpperCase(str) || isLowerCase(str)){
	 	var lcStr = str.toLowerCase();
    	return lcStr.replace(/(?:^|\s)\w/g, function(match) {
       	 	return match.toUpperCase();
    	});	
	} else {
		return str;
	}
}

I am mostly trying to contend with the users WHO INSIST ON YELLING THEIR DATA ENTRY! It's one thing for internal data, but when customers are going to see it, I have to draw the line.