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:

    text-transform: uppercase;

Weeee ^_^ Ok, back to work…

  • Nicolas

    or :”capitalize”

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

  • ling maaki

    You can use RegEx too

    function titleCaseReg(inStr)
    retrun inStr.replace(/^[a-z]/,function(str)
    retrun str.toUpperCase()

    Full Source ….Capitalize the first letter


  • Hemali Sanghvi

    lorem impsum

    for javascript :
    document.getElementById(“textcaptialized”).style.textTransform = “capitalize”;

    for JQuery:

    • I’d much rather set CSS like this through a stylesheet than in Javascript. And if it needs to be toggled on or off for some reason, I’d prefer using a class.