Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the toUpperCase() method

In JavaScript there is no shortcut function like the PHP ucfirst() to make the first letter or character of a string to uppercase. However, you can achieve the same thing using the JavaScript toUpperCase() method in combination with the charAt() and slice() methods with a little trick.

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 is optional and if it is omitted, the slice() method extracts to the end of the string.

Characters in a string are indexed from left to right. The index of the first character is 0, while the index of the last character in a string variable called str would be str.length - 1. To better understand all this, let's check out the following example:

<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 our 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 string excluding the first character and concatenates them finally and return it.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Create Multiline Strings in JavaScript... >>
<< How to get the value of a textarea in jQuery...