How to make the first letter of the string Uppercase in JavaScript

While JavaScript doesn’t have its own function to do this, like PHP’s ucfirst() we can achieve a similar result on our own.

Just use a combination of charAt(0), toUpperCase() and slice(1) to use the toUpperCase() function only on the first character.

<script>
    str.charAt(0).toUpperCase() + str.slice(1);
</script>

Example:

<script>
    var str = 'uppercase string.';
    str = str.charAt(0).toUpperCase() + str.slice(1);

    console.log(str)
</script>

Output (console): Uppercase string.

Function to make a first letter Uppercase in JavaScript

Wanna use this often? Here’s the ready-to-use function.

<script>
    function ucFirst(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
</script>

Example:

<script>
    function ucFirst(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }

    // Example:

    console.log('the quick brown fox'); // Output: the quick brown fox
    console.log(ucFirst('the quick brown fox')); // Output: The quick brown fox
</script>