Title case sentences

**Hello this is my code for this challenge when i test it it working but the interpreter does’nt validate my code **


function titleCase(str) {
let words, capitalizeSentence = '';
words = str.toLowerCase().split(' ')
 for (let i = 0 ; i<words.length; i++){
   capitalizeSentence += words[i][0].toUpperCase()
   capitalizeSentence += words[i].slice(1)
   capitalizeSentence += ' '
 }
 console.log(capitalizeSentence)
return capitalizeSentence;
}

titleCase("I'm a little tea pot");
//titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")
//titleCase("sHoRt AnD sToUt")

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 12499.73.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.113 Safari/537.36.

Challenge: Title Case a Sentence

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence

This is your code, with added console.log statements, check those to figure out what’s wrong.

function titleCase(str) {
  console.log(str.length) // 20
  let words, capitalizeSentence = '';
  words = str.toLowerCase().split(' ')
  for (let i = 0; i < words.length; i++) {
    capitalizeSentence += words[i][0].toUpperCase()
    capitalizeSentence += words[i].slice(1)
    capitalizeSentence += ' '
  }
  console.log(capitalizeSentence.length) // 21
  return capitalizeSentence;
}

titleCase("I'm a little tea pot");
//titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")
//titleCase("sHoRt AnD sToUt")

hi thanks you i saw the error , the length of the string i return is greather than the initial string length because i add one more blank space after the last words , thank for the help , i didn’t notice this before .

1 Like

good job! now just figure out how not to add it, and you are all set!
Happy coding!

yes i fix it already , thank you very much

…Hello guys, This is my code for this challenge, i tend to take a different on this challenge and it came out well. Code edited and working perfectly

  function titleCase(str) {
    let  arr = str.split("");
     let z = 0;
       for(var i = 0; i < arr.length ; i++){
            if(arr[i] == " "){
                 z = 0;
            }
            else { if(z == 0){
                 arr[i] = arr[i].toUpperCase();
                 z = 1
            }else{
                  arr[i] = arr[i].toLowerCase();
                 }
            }
        }
      
       return arr.join("")
    }
  

I was wondering if there is a way to refer to the character which comes after the white space. Can you use (\s + 1)?