48

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

Alex
  • 143
  • 2
  • 14
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

13 Answers13

77

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"
Ben Blank
  • 54,908
  • 28
  • 127
  • 156
  • 1
    While the CSS solution below works, it does NOT replace the value of an input with the TitleCase return. It just gives the VISUAL that it has been done. This solution worked well for me. – Sam Grant Mar 06 '13 at 16:57
  • Furthermore, you don't need javascript at all! You can do this via CSS as laid out below. – TNC Mar 20 '13 at 22:36
  • 5
    @TNC — A CSS solution may well be a better solution to the asker's original *problem*, but it doesn't actually address the asked *question* (how to alter a "string"). While the mention of jQuery strongly implies it, the question never actually states that there's a browser involved; it's possible, after all, that they could be using [jQuery in Node](http://stackoverflow.com/questions/1801160)! ;-) – Ben Blank Mar 24 '13 at 02:13
  • I looked here ... https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp ... but could not figure out what `^|` is doing as `^` means either match at the beginning or negating a character set. `|` is a boolean or. But what is the non-capturing group `(?:^|\s)` doing exactly? –  Apr 04 '13 at 15:01
  • @livingston_mechanical — It means "the beginning of the string or a whitespace character". – Ben Blank Apr 06 '13 at 02:09
  • Even in the browser you might want to actually alter the string for some kind of processing (though since it's unclear, the CSS solution should be stated just in case it does suffice) – Ingo Bürk Sep 11 '13 at 17:56
  • This doesn't capitalize the first letter when preceded by a `(` character – Keyslinger Feb 09 '22 at 00:15
49

You can use css, like:

.className 
{
    text-transform:capitalize;
}

This capitalizes the first letter. You can read more here

TNC
  • 5,388
  • 1
  • 26
  • 28
  • 5
    Seriously. This is the correct answer. All others are just silly and WAY over the top. If you MUST have jQuery, then try this: $('#test').css('textTransform', 'capitalize'); – vbullinger Oct 09 '12 at 20:57
  • 3
    I don't think this properly answers the question since this string might never be used in an HTML context. – just_wes May 10 '13 at 20:13
  • just_wes it doesn't implicitly say either way. Perhaps you should revisit what down votes are for. – TNC May 10 '13 at 20:51
  • 3
    @TNC, the OP mentions wanting a solution for jQuery. To me this implies that he is looking for a way to do this with jQuery or Javascript. But considering that a large base of jQuery users are doing simple DOM transformations, I think you're right. – just_wes May 17 '13 at 21:40
  • 6
    @TNC this is great if the string is in the DOM, but if you want to camelcase something in Javascript, this answer is obviously incorrect. – Jason Jul 09 '13 at 20:14
  • This also work as the best most efficient way, the Regex always eats cycles no matter how you slice it (well maybe in the present its almost negligible, but when you send that to a subpar device, say, an android phone that's not so good, it makes a great difference) – Luis Robles Oct 01 '13 at 21:45
  • 6
    This is a bad answer. It do what the asker asked for in the first place, it doesn't camelize a string, it changes how text is **displayed**. There are many reasons to camelize a dasherized string that you don't want to display, for example jQuery does so when it let's you do `.css('font-size', aSize)` to set `.style.fontSize = aSize`, which, further, makes it reasonable to assume jQuery exposes a method to do so. And even if changing the display is what the asker wanted, it's less reliable due to [browser bugs](http://reference.sitepoint.com/css/text-transform#compatibilitysection). – Han Seoul-Oh Jun 26 '14 at 00:21
  • 1
    If every letter in the text is capitalized then this solution does nothing, in order to make this solution consistent you will need to modify the text with 'text.toLowerCase();' – ricks Jan 31 '19 at 21:53
21

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.

Pjotor
  • 227
  • 1
  • 2
  • 5
    Seems like an undocumented internal function; with something this simple it might be better to simply write out the function yourself instead of relying on something that may get pulled at any time. Looking at [the source](http://james.padolsey.com/jquery/#v=1.5&fn=jQuery.camelCase) for this function, you can see how you can easily do this – Yi Jiang Mar 01 '11 at 11:14
  • Here's the doc :) http://robflaherty.github.com/jquery-annotated-source/docs/01-core.html – Pierre Aug 04 '12 at 00:56
  • 8
    `jQuery.camelCase('bob smith') = 'bob smith'` but the question asked to turn it into Bob Smith. – Pikachu Mar 12 '14 at 20:37
  • 1
    Note that this function will be removed: https://github.com/jquery/jquery/issues/3384 – Jens Apr 13 '20 at 00:30
13

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"
RBizzle
  • 151
  • 1
  • 5
4

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

Ramiro
  • 41
  • 1
4

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);
Seth
  • 6,240
  • 3
  • 28
  • 44
2

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);
}
Joon
  • 9,346
  • 8
  • 48
  • 75
2

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()
Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
1
    function camelCase(str){
        str     = $.camelCase(str.replace(/[_ ]/g, '-')).replace(/-/g, '');
        return  str;//.substring(0,1).toUpperCase()+str.substring(1);
    },
surinder singh
  • 1,463
  • 13
  • 12
1

Use inbuilt camelcase method in jquery:

$.camelCase($("#text").html());
Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
0
<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>
SajithG
  • 130
  • 4
0

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(); });
    }
Pritam Jyoti Ray
  • 320
  • 1
  • 8
  • 12
0

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.