-1

The below code is supposed to capitalize all the words in a string, but it is not working. The string is split and put back together appropriately except the toUpperCase method is not even working on the first character.

function titleCase(str) {
  let strArray = str.split('');
  strArray[0].toUpperCase();
  for(let i=1;i<strArray.length;i++){
    if(strArray[i-1]===' '){
      strArray[i].toUpperCase();
    }
  }
  return strArray.join('');
}

let titleStr = titleCase("i'm a little tea pot");
console.log(titleStr);
  • 1
    Strings in JavaScript are immutable. You can't modify them but you can create a modified string and store it in the old variable. – Thomas Sablik May 23 '21 at 20:57

1 Answers1

1

toUpperCase do not modifies variable itself, instead it returns a new one, so you need to reassign it.

e.g. this line is doing nothing strArray[0].toUpperCase();, cause you forgot to assign it somewhere, same line inside your for-loop.

Working solution based on your code:

function titleCase(str) {
  let strArray = str.split('');
  strArray[0] = strArray[0].toUpperCase();
  for(let i=1;i<strArray.length;i++){
    if(strArray[i-1]===' '){
      strArray[i] = strArray[i].toUpperCase();
    }
  }
  return strArray.join('');
}

let titleStr = titleCase("i'm a little tea pot");
console.log(titleStr);
ulou
  • 5,542
  • 5
  • 37
  • 47
  • I see that it does nothing but I do not understand why. There has to be an assignment somewhere? Thanks – Dylan Stechmann May 23 '21 at 20:58
  • Yes, `toUpperCase` do not modifies variable itself, instead it returns a new one, so you need to reassign it as you see in code above. – ulou May 23 '21 at 21:01