'replace' undefined

Tell us what’s happening:

Alright, I’m stuck. I feel like my code makes sense… but I keep getting this error in the console: “TypeError: Cannot read property ‘replace’ of undefined”

Any hints/tips?

Your code so far


function titleCase(str) {
let upperCaseArr = [];
let strLowerCase = str.toLowerCase();
let splitStr = strLowerCase.split(" ");
for (let i = 0; i < strLowerCase.length; i++) {
   let upperCaseFirst = splitStr[i].replace(splitStr[i].charAt(0), splitStr[i].charAt(0).toUpperCase());
   upperCaseArr.push(upperCaseFirst);
   
}
return upperCaseArr.join(" ");
}

titleCase("I'm a little tea pot");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36.

Challenge: Title Case a Sentence

Link to the challenge:

You’re looping over the length of the string. So “I’m a little tea pot” will loop 20 times, but splitString[i] is undefined by the 6th iteration. undefined doesn’t have a method replace

1 Like

Thank you very much :slight_smile:

1 Like