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(' ')
}
  • You have to assign the output of `toLowerCase()` and `toUpperCase()`, they don't modify in-place – Nick Apr 04 '20 at 01:19
  • [Here](https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript) – trinaldi Apr 04 '20 at 01:19

1 Answers1

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'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320