How to capitalize the first letter of a string in JavaScript?
Hi everyone! I just started learning JavaScript and came across this task: I need to write a function that takes a string and returns it with the first letter capitalized. For example, "hello world" should become "Hello world".
I tried to do this using charAt and toUpperCase, but it doesn't work as expected. Here's my code:
```javascript
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase();
}
console.log(capitalizeFirstLetter("hello")); // Outputs only "H", but should output "Hello"
```
The problem is that the function returns only one letter, not the entire string. I understand that I need to somehow preserve the remaining characters, but I don't know how to do it correctly. I tried using slice, but got confused.
Also, I noticed that if the string is empty, the code returns
No answers yet.
Log in to leave an answer