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

Answer: Use the toUpperCase() method

JavaScript does not have a shortcut function such as the PHP ucfirst() that will make the first letter of a string uppercase. You can however achieve the same result using JavaScript  toUpperCase()in combination with the  charAt()  or  slice() plans. However, this requires some trickery.

The  charAt()  method return the character at the specified index, whereas the  slice() method extracts a section of a string based on the  beginIndex  and  endIndex  parameters, like this str.slice(beginIndexendIndex). The endIndex  parameter can be optional and the slice() method will extract the string to its end if it is not.

Indexes are used to index characters in strings from left-to-right. The index of the first character of a string variable is 0. While the index of  str  last character would be  str.length - 1.  Let’s take a look at the following example to better understand all of this:

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

What are custom function  capitalizeFirstLetter() does in the above example is, get the first character of the string and convert it to uppercase using the  toUpperCase() method, then extract the portion of the series excluding the first character and concatenates them finally and return it?

Exit mobile version