JavaScript: Capitalize the first letter in a string.

This is a guide on how to capitalize the first letter in a JavaScript string. This can be particularly useful if you are “cleaning up” the display of people’s names or sentences.

Capitalizing the first letter in a string.

Below, I have created a JavaScript function that will convert the first character of a string into an uppercase format. Note that this function may seem long-winded and verbose. However, it is purposely written that way so that the reader can better understand what is actually going on. A more concise version can be found further down the page.

//A JavaScript version of the PHP function ucfirst, which can
//be used to capitalize the first letter of a string.
function ucfirst(str) {
    //Get the first character of the string.
    var firstChar = str.charAt(0);
    //Convert the first character to uppercase.
    firstChar = firstChar.toUpperCase();
    //Remove the original uncapitalized first character.
    var strWithoutFirstChar = str.slice(1);
    //Add the capitalized character to the start of the string.
    var newString = firstChar + strWithoutFirstChar;
    //Return it
    return newString;

An overview of the function above, which is named ucfirst:

  1. We got the first letter of the string using the charAt() method. Remember that the first character in a string will always have the index “0”.
  2. After we retrieved the first character, we were able to convert it into uppercase by using the method toUpperCase().
  3. We then removed the first character from the original string.
  4. Finally, we add the new capitalized version of the character onto the front of the string and return it.

The function above can be shortened down into a more concise version:

//Convert the first char of a string to uppercase
function ucfirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);

Our new function can be used like so:

//An example JavaScript string. In this case, it is
//a person's name.
var name = 'brenda';

//Test our ucfirst function.
alert(name + ' becomes ' + ucfirst(name));

If you run the snippet above, you should get the following:

brenda becomes Brenda

OO approach with String.prototype

You can also take a more Object Orientated approach by extending the native String object. However, I would recommend against doing this unless it is completely necessary.  The problem with extending a native object is that you are essentially modifying its behavior. This can cause bugs in other pieces of code and libraries that are using the same object.

However, if you must extend the String object, then you can use the following example:

//Extending the native String object.
String.prototype.ucfirst = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);

var name = 'wayne';
alert( name.ucfirst() );

And that’s it! Hopefully, this guide helped you out!