How do I use JavaScript to capitalize the first letter of a string?

How do I use JavaScript to capitalize the first letter of a string?

Hello Saanvi,

Using charAt() and toUpperCase():

function capitalizeFirstLetter(str) { return str.charAt(0).toUpperCase() + str.slice(1); }

// Example usage console.log(capitalizeFirstLetter(“hello”)); // Output: “Hello”

This function capitalizeFirstLetter takes a string str as input and capitalizes its first letter. Here’s a breakdown of how it works:

  1. str.charAt(0): This extracts the first character of the input string str.
  2. toUpperCase(): This method is used to convert the first character to uppercase.
  3. str.slice(1): This extracts the rest of the string starting from the second character. It effectively removes the first character from the string. 4, Concatenation (+): The capitalized first character and the rest of the string are concatenated together to form the final capitalized string.

So, for the input “hello,” the function returns “Hello” by capitalizing the first letter “h.”

I hope this answer will works for you, please let me know if you need any further clarification.

Hello Saanvi,

Using array destructuring and toUpperCase():

function capitalizeFirstLetter(str) { const [first, …rest] = str; return [first.toUpperCase(), …rest].join(‘’); }

// Example usage console.log(capitalizeFirstLetter(“hello”)); // Output: “Hello”

This capitalizeFirstLetter function takes a string str as input and capitalizes its first letter. Here’s how it works:

  1. const [first, …rest] = str;: This line uses array destructuring to extract the first character of the input string str into the variable first, and the rest of the characters into the array rest.
  2. return [first.toUpperCase(), …rest].join(‘’);: Here, first.toUpperCase() capitalizes the first character, and [first.toUpperCase(), …rest] creates a new array with the capitalized first character followed by the rest of the characters. Finally, join(‘’) combines all the characters back into a single string.

So, for the input “hello”, the function returns “Hello” by capitalizing the first letter “h” using array destructuring and toUpperCase().