Title Case a Sentence code doesn't work

Hey,

Can somebody help me understand why this code doesn’t work? I know it’s not the best way to solve it but it should work in this exercise. I’m fairly lost.

Thank you.

The code is:


function titleCase(str) {
  var x = str.split('');
  var regEx = /^\w/i;
  
 for(var i = 0; i < x.length; i++){
    if(regEx.test(x[i])===true){
      x[i]=x[i].toUpperCase();
    } 
    if(regEx.test(x[i])===false){
      x[i]=x[i].toLowerCase();
    }
  }
console.log(x);
return x;

}

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

Your browser information:

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

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

The goal of this challenge is to return a string where every word begins with a capital letter. What your function returns an array of letters, all of which are capitalized.

@ArielLEslie is right.

Before start to code you need to make the algorithm and think clear about what your function it is suposed to do

  1. Your function will consume a String
  2. Your function will return a string
  3. You will iterate all the string, the iteration will be:
    3.1)The first character always will be a capital letter.
    3.2) From the second character up to the end you will have a capital letter if there is a space before that letter, otherwise will be a lower case letter.
    3.3) You will append all produced letters to the returned string.
    3.4) Once you have iterated all letters you return the new string.

So with all that given you should find:

  1. A method to iterate a string
  2. A method to produce and append letters to a new string
  3. A flow to know if the character is the first character of the given string
  4. A flow to know if the character is a white space
  5. A method to covert a lower case to upper case
  6. A method to convert a upper case to lower case.

A you are done.

1 Like