In JavaScript, What Is The Method To Capitalize The First Letter Of A String?

In JavaScript, you can convert the first letter of a string to uppercase using the charAt() and toUpperCase() methods. Here’s an example:

let str = "hello world";
let firstChar = str.charAt(0).toUpperCase();
let capitalizedStr = firstChar + str.slice(1);

console.log(capitalizedStr); // Output: "Hello world"

Explanation:

  1. Declare a variable str and assign the string you want to modify.
  2. Use the charAt() method with the index 0 to extract the first character.
  3. Apply the toUpperCase() method on the first character to convert it to uppercase.
  4. Use the slice() method on the original string (str) starting from the second character (index 1) to get the rest of the string.
  5. Concatenate the uppercase first character with the rest of the string using the + operator.
  6. Finally, print the modified string (capitalizedStr) which has the first letter capitalized.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!