JavaScript practice

Hello Everyone, I’m practicing through this activity (http://shorturl.at/cgtNS) Write a function called capitalize that takes a string and returns that string with only the first letter capitalized. Make sure that it can take strings that are lowercase, UPPERCASE, or BoTh. and here is my solution to this activity

 function capitalize(string){
          
          return string.charAt(0).toUpperCase() + string.slice(1);
 };

 console.log(capitalize());`

which I’m not quite sure about it if that is what exactly the activity wants me to do.
any hint will be appreciated.

Hi @blue_sky and welcome to the community :wave:

I think you should add .toLowerCase() to the second part. Then it would also correctly format a string like “wELCoMe to The comMUniTy!”

I hope that helps!
Michael

1 Like

that makes sense thanks for your reply.

1 Like

I’ve changed the whole structure of the code and finally, it worked but could you please give me feedback about it so I can improve it
thank you again! :smiley:

`function capitalize(){
   let writeText = prompt("write your text here.");
   let firstLetter = writeText.charAt(0).toUpperCase();
   let TheRest = writeText.slice(1).toLowerCase();
   let allThem = firstLetter + TheRest;
    return allThem;
 };
 console.log(capitalize());`

That looks pretty clean. Well done!
The only thing I would change is all the lets to consts. It’s generally recommended to use const by default and only use let when the value is going to change.

1 Like

Hello, I am doing the same practice at the moment and I think I found a shorter version for this exercise:

<script>
       function capitalize(string) {
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
       }
       console.log(capitalize("UppErCaSe"));
</script>

Let me know what you think.

1 Like

Hi @iulian.corut10 and welcome to the community :wave:

That’s an elegant solution. I like it :heart_eyes:

That’s great, clean and concise​:+1::ok_hand:

1 Like
//Capitalize
let capitalize = (something) => {
    let firstChar = something.charAt(0).toUpperCase();
    let remainStr = something.slice(1).toLowerCase();
    return firstChar + remainStr
}

console.log(capitalize("anY StrinG heRE"));