How to make the first letter of a string uppercase using JavaScript



Definition and Usage

charAt() is a very useful function in Javascript and all the related Object Oriented Programming concepts. The function acts to extract and return individual characters at a designated index on a particular string. It however acts with taking the first character of a string to be as 0. This is very useful to calculate the positions of a string, especially to calculate the position and length of a phrase or a word. The chief criteria of using this function should be the length from 0 to length()-1.


This will return the 2nd character index of a string.

However, the function follows certain set of exceptions, of which the most commonly observed is the IndexOutOfBoundsException. This parameter appears in the comment line section if the array index is lesser than 0 or is greater than or equal to that of the length().

Example explaining charAt() to convert the first letter of a string to uppercase using javascript.



    // Define function to capitalize the first letter of a string

    function capitalizeFirstLetter(string){

        return string.charAt(0).toUpperCase() + string.slice(1);



    // Calling function and display the result

    var str1 = 'hi there!';

    str1 = capitalizeFirstLetter(str1);

    document.write(str1); // Print: Hi there!


    var str2 = 'the Gods must be crazy.';

    str2 = capitalizeFirstLetter(str2);

    document.write(str2); // Print: The Gods must be crazy.


    var str3 = '/app/index.html';

    str2 = capitalizeFirstLetter(str3);

    document.write(str3); // Print: /app/index.html


In this code, a non-void returnable function with a string parameter is passed. The string character is returned with the first index, which is 0 and called by the charAt(0). This is converted to uppercase using toUpperCase() function.

Moreover, the presence of slice() function, allows to extract parts of a string and returns a newer string.

Next part is the function calling, where the result of a function is displayed. Mostly, the function is used as a one-step measure to convert the input string.

For an instance, “hi there!” is stored in string called str1, which is called as a parameter inside the main function capitalizeFirstLetter. Thus, it prints “Hi there!” Similarly, the other strings, i.e. str2, str3 too gives away similar results with first character transformed to Upper Case.

charAt() function also works for looping parameters, where more than a small set of characters might be required to trigger and get extracted. However, the iterative process of looping should always have a maximum range to the length()-1 to that of the string value.

View Demo

↑ Back to Top