AnApprentice
AnApprentice

Reputation: 110940

jQuery Title Case

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

Upvotes: 48

Views: 76158

Answers (13)

Cheryl Miller
Cheryl Miller

Reputation: 66

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.

Upvotes: 1

Pritam Jyoti Ray
Pritam Jyoti Ray

Reputation: 330

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(); });
    }

Upvotes: 0

SajithG
SajithG

Reputation: 130

<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>

Upvotes: 0

RBizzle
RBizzle

Reputation: 161

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"

Upvotes: 14

Xameer
Xameer

Reputation: 31237

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()

Upvotes: 3

Nalan Madheswaran
Nalan Madheswaran

Reputation: 10562

Use inbuilt camelcase method in jquery:

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

Upvotes: 1

Ramiro
Ramiro

Reputation: 41

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...

Upvotes: 4

Joon
Joon

Reputation: 9874

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);
}

Upvotes: 2

surinder singh
surinder singh

Reputation: 1555

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

Upvotes: 1

Pjotor
Pjotor

Reputation: 225

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.

Upvotes: 20

Ben Blank
Ben Blank

Reputation: 56572

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"

Upvotes: 77

TNC
TNC

Reputation: 5386

You can use css, like:

.className 
{
    text-transform:capitalize;
}

This capitalizes the first letter. You can read more here

Upvotes: 49

Seth
Seth

Reputation: 6260

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);

Upvotes: 4

Related Questions