Code isn't passing for Title Case a Sentence [SOLVED]

function titleCase(str) {

  var newStr = "";
  var myArr = str.toLowerCase().split(" ");
    for (i = 0; i < myArr.length; i++) {
    newStr += (myArr[i][0].toUpperCase() + myArr[i].substring(1, 25) + " ");  
  return newStr;

titleCase("i'M A litTLe TEa PoT");

As far as I can see my code does exactly what the instructions ask, and is spitting out the correct results in my test. However I’m not passing the validation and unable to move on. Is this a bug, or have I done something weird here I’m not seeing?

This. Try your code on to see what I mean :wink:

1 Like

Pardon my ignorance but the only thing I can see that is maybe causing a problem is that my code add’s a space between each word when it puts it back into a string, and this includes the last word so that the string ends with a space ie ("This is a test string "). Is this what’s giving my trouble? If so how could I compile the string to not add a space at the end?

I am by no means an expert but when I did this one (five minutes ago), I had an additional step where I made a new array, then used join for the string that was submitted for validation. That way there wasn’t a space on the end.

Also, my understanding of the substring method is that if the second argument is left out, it will just return the rest of the characters in the string, so you might not need that 25?

1 Like

That’s indeed the case. There are many ways to not have a space at the end, but the easiest is to use .trim().

1 Like

@paintingfire - You are absolutely correct, I did not need the 25 in there.

@kevcomedia - .trim() !!! Can’t believe it was simple as that! Cheers mate :smiley:

If u could please tell me why this code is not getting a green signal

function titleCase(str) {
var lowstr = str.toLowerCase();
splitt = lowstr.split(" “);
len = splitt.length;
var val =”" ;

for(var i=0; i<len;i++){

val += splitt[i][0].toUpperCase() + splitt[i].substring(1,splitt[i].length)+" ";

return val;

it does return the output as needed but does not get a green signal