Question
Answer and Explanation
To capitalize the first letter of a string in JavaScript, you can use a combination of string methods. Here's a breakdown of how to achieve this:
1. Extract the First Letter:
- Use the charAt(0)
method to get the first character of the string.
2. Convert to Uppercase:
- Apply the toUpperCase()
method to the first character you extracted.
3. Get the Rest of the String:
- Use the slice(1)
method to get the remaining portion of the string, starting from the second character.
4. Combine the Capitalized Letter and Remaining String:
- Concatenate the capitalized first letter with the rest of the string.
Here's the JavaScript code illustrating these steps:
function capitalizeFirstLetter(string) {
if (!string) return ""; // Handle empty or null strings
return string.charAt(0).toUpperCase() + string.slice(1);
}
const myString = "hello world";
const capitalizedString = capitalizeFirstLetter(myString);
console.log(capitalizedString); // Output: "Hello world"
const anotherString = "javascript is fun";
const anotherCapitalized = capitalizeFirstLetter(anotherString);
console.log(anotherCapitalized); // Output: "Javascript is fun"
Explanation of the Code:
- The function capitalizeFirstLetter
takes a string
as an argument.
- It first checks if the string is empty or null
. If so, it returns an empty string.
- If the string is valid, string.charAt(0)
gets the first character, which is then converted to uppercase using toUpperCase()
.
- string.slice(1)
gets the rest of the string (from the second character onwards).
- Finally, the uppercase first character and the remaining string are concatenated and returned.
Usage Example:
- We have two example strings, myString
and anotherString
.
- When the function is called with these strings, it returns new strings with the first letter capitalized.
- The results are then printed to the console.
This method is straightforward and effective for capitalizing the first letter of any string in JavaScript.