JavaScript: Uppercase first letter in a string

Published:

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