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 method

In some cases it might be good to handle this in CSS instead though. 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…

This entry was posted in Software Development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>