JavaScript: Capitalize the first letter of a string.

In this tutorial, we will show you how to capitalize the first letter of a string using JavaScript.

This can be useful if you are formatting people’s names, nouns, or sentences.

How to capitalize the first letter in a string using JavaScript.

The JavaScript function below will convert the first character of a string into its uppercase format:

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

}

This function might seem a bit long-winded. However, we purposely wrote it that way so you can better understand what it is doing.

An explanation of the code above:

  1. We get 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 retrieving the first character, we convert it into uppercase using the method toUpperCase().
  3. We then remove the first character from the original string.
  4. Finally, we add the capital letter to the front of the string and return it.

Now that we understand what is happening, let’s shorten our code and condense it:

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

Here is an example of the function in use:

//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 JavaScript code above, you will get the following output:

brenda becomes Brenda

Using String.prototype.

If you are looking for an object-oriented (OO) solution, then you can extend the native String object.

However, we recommend that you do not do this unless it is absolutely necessary.

The problem with extending the String object is that you are modifying its behavior. This can cause bugs in other pieces of code and libraries that are also using it.

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

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

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

In the code above, we created a new object method that will capitalize the first letter of a string. We were then able to call that method like any other.