0

i have tried the code below and its not working

function capFirstLetter(str) {
 let arr = str.split(' ')
 for (let i = 0; i < arr.length; i++) {
 const word = arr[i];
 word.toLowerCase()
 word[0].toUpperCase()
 }
 return arr.join(' ')
}

asked Apr 4, 2020 at 1:17
2
  • You have to assign the output of toLowerCase() and toUpperCase(), they don't modify in-place Commented Apr 4, 2020 at 1:19
  • Here Commented Apr 4, 2020 at 1:19

1 Answer 1

3

Strings are immutable. Calling toLowerCase() or toUpperCase() on a string results in a new string. If you want to use that new string, you have to return it or assign it to something, or something like that.

Here, take the first letter and call toUpperCase on it. Then concatenate it with the rest of the letters which have toLowerCase called on them:

function capFirstLetter(str) {
 return str.split(' ')
 .map(word => word[0].toUpperCase() + word.slice(1).toLowerCase())
 .join(' ');
}
console.log(capFirstLetter('foo bAR'));

answered Apr 4, 2020 at 1:21
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.