What am I missing regarding the toUpperCase() method?

I am trying to make capitalized the first letter of each word via toUpperCase() method and the rest of the word is in the lower case via the toLowerCase() method. But I am missing something… Why ’ temp ’ value is not matching with ’ result[1][0] ’ even I am using that method for both? Note: I know the other ways(Map ,replace…) for my solution. But , I want to use just for-loop with toUpperCase() and toLowerCase() methods… I have just some questions about that toUpperCase() method for now.

 function titleCase(str) {
  let regex = /[^0-9\s]+/g;
  var result = str.match(regex);
  let temp = "";
  for (let i = 0; i < result.length; i++) {
    for (let j = 0; j < result[i].length; j++) {
        result[1][0] = result[1][0].toUpperCase();
        temp = result[1][0].toUpperCase();
    }
  }

  console.log(temp); // Output is 'A'
  console.log(result[1][0]); //Output is 'a'
  // Normally 'temp' and 'result[1][0]' should be equal, but one returns a lowercase character and the other an uppercase character.
  return str;
}

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

In JS strings are immutable, i.e. result[1] is a string and you’re trying to change a single character in string, but because strings are immutable nothing happens.

2 Likes