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(' ')
}
1 Answer 1
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
CertainPerformance
373k55 gold badges354 silver badges359 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
toLowerCase()andtoUpperCase(), they don't modify in-place