JavaScript: Uppercase first letter in a string

In PHP there is a very handy function called ucfirst which

Returns a string with the first character of str capitalized, if that character is alphabetic.

Needed that in JavaScript, but discovered there was no such thing.

Luckily I quickly found a function over at StackOverflow that I adjusted slightly and added to the string class:

String.prototype.ucfirst = function()
{
    return this.charAt(0).toUpperCase() + this.substr(1);
}

Can be used like so:

alert('some text'.ucfirst())
// Alerts: Some text

Alternative CSS method

In many cases it might be good to just handle this with CSS instead. For example, to uppercase the first letter in all list items, you can do this:

li:first-letter
{
    text-transform: uppercase;
}

Weeee ^_^ Ok, back to work…

  • Nicolas

    or :

    this.style.textTransform=”capitalize”

    • http://www.geekality.net/ Torleif Berger

      But that would be using CSS. Which is fine in many cases, but sometimes it’s necessary to actually fix the data behind too and not just what the user see. When it only matters for the user what they see, then CSS is a great way though :)

  • Robin

    Hi! Great tip but did you know that .substr() is actually a bit slower than .substring() ?

    I’ve put together a list of different approaches to this problem on my blog, including a speedtest for each one of them. You can find the fastest way to convert the first letter to uppercase here:

    http://forwebonly.com/capitalize-the-first-letter-of-a-string-in-javascript-the-fast-way/