How To Capitalize The First Letter Of A String In JavaScript

Here is the quick JavaScript code snippet to capitalize the first letter of a string.

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

How to use

let string = 'hello world';
 console.log(ucFirst(string));  // output: Hello World

Details of each function which we used to capitalize the first letter of a given string.
charAt() return the character at a certain index of a string. Here string.charAt(0) means selecting first character.

toUpperCase() function convert the string to uppercase letters. Here string.charAt(0).toUpperCase() means select the first character and convert it to uppercase

slice() function return the selected elements from an array. Here string.slice(1) will allow us to get the rest of the string and remove the first letter.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems. Protection Status