Title Case a Sentence query

So i wrote the following code

function titleCase(str) {
  let newstr = "";  
  let lcase = str.toLowerCase();  
  let splitStr = lcase.split(" ");  
  for( let i = 0; i < splitStr.length; i++){
    let first  = splitStr[i].charAt();      
    let ucase = first.toUpperCase();    
    let remain = splitStr[i].slice(1);      
    newstr = newstr + " " + ucase + remain;    
  }   
  return newstr;
}

titleCase("sHoRt AnD sToUt");

When i console log newstr, it shows the correct output, but when i run the tests it doesn’t pass. What am i missing here?

Try adding these logs.

console.log("I'm A Little Tea Pot" === titleCase("I'm a little tea pot"))

console.log("I'm a little tea pot".length)
console.log(titleCase("I'm a little tea pot").length)

console.log(JSON.stringify(titleCase("I'm a little tea pot")))
2 Likes

Thank you - i understood the error was an additional space as the lengths weren’t matching.

So, after trying a bit to move the space here and there which didnt work, i did the following and it worked

function titleCase(str) {
  let newstr = [];  
  let newstr2;
  let lcase = str.toLowerCase();  
  let splitStr = lcase.split(" ");  
  for( let i = 0; i < splitStr.length; i++){
    let first  = splitStr[i].charAt();      
    let ucase = first.toUpperCase();    
    let remain = splitStr[i].slice(1);          
    newstr.push(ucase + remain);
    newstr2 = newstr.join(" ");
  }     
  return newstr2;  
}

titleCase("sHoRt AnD sToUt");

i don’t know if its elegant though :sweat_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.