Basic Algorithm Scripting - Title Case a Sentence

Tell us what’s happening:
I’m sure I’m missing something, but when I submit my code for this challenge, it is not accepted despite each example input producing the desired output.

Your code so far

function titleCase(str) {
  let splitString = str.split(" ");
  let newString = "";
  
  for (let i = 0; i < splitString.length; i++){
/* 
    -The splitString[i][0].toUpperCase() capitalizes
    and adds the first letter of each index to newString

    -The splitString[i].slice(1).toLowerCase() adds the
    rest of the word in each index while removing the 1st
    letter and ensuring everything else is lowercase

    -The ' ' ensures that each word has white space between it
*/
    newString += splitString[i][0].toUpperCase() + 
    splitString[i].slice(1).toLowerCase() + ' ';
  }return newString 
}

console.log(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/112.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Title Case a Sentence

Link to the challenge:

Minor formatting fix

function titleCase(str) {
  const splitString = str.split(" ");
  let newString = "";

  for (let i = 0; i < splitString.length; i++) {
    /* 
        -The splitString[i][0].toUpperCase() capitalizes
        and adds the first letter of each index to newString
    
        -The splitString[i].slice(1).toLowerCase() adds the
        rest of the word in each index while removing the 1st
        letter and ensuring everything else is lowercase
    
        -The ' ' ensures that each word has white space between it
    */
    newString += splitString[i][0].toUpperCase() +
      splitString[i].slice(1).toLowerCase() + ' ';
  }
  return newString
}

console.log("***" + titleCase("I'm a little tea pot") + "***");

Try this console.log statement I added to your code.

Hey I just figured it out, since I’m adding whitespace at the end of each iteration through the loop, after the last word, whitespace is added as well. So now I have the option of either removing the whitespace at the end of the loop, or a could find a different method.

1 Like

Thank you, I was on the verge of pulling my hair out! Would the best play be to simply pop() the end of the string?

This function is designed for this sort of thing:

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