- Extract the first character of the string using the “charAt()” method or by accessing it with the “index ”.
- Convert the first character to uppercase using the “toUpperCase()” method.
- Extract the rest of the string from the second character using the “slice()” method.
- Concatenate the uppercase first character and the rest of the string.
const inputString = "hermione granger"; const capitalizedString = inputString .charAt(0) .toUpperCase() + inputString.slice(1); console.log(capitalizedString);
In this code, we first used the “charAt(0)” method to extract the first character of the inputString variable (‘hermione granger’).
In the next step, we used the “toUpperCase()” method to convert the first character to uppercase (‘H’).
Next, we used the slice(1) method to extract the rest of the string starting from the second character (‘ermione granger’).
Finally, we concatenated the uppercase first character and the rest of the string to obtain the capitalized string (‘Hermione granger’).
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.