JavaScript subarray Iteration

I want to capitalize the first letter of every word in a string.

I want to know why this is not working:

function titleCase(str) {
  str = str.toLowerCase().split(" ");
  for(let i = 0; i<ar.lrngth;i++){
    ar[i][0] = ar[i][0].toUpperCase();
  }
  return ar;
}

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

Nor this:

function titleCase(str) {
  str = str.toLowerCase().split(" ");
  let _ar = [];
  _ar =str.map(item => item.map( cap => cap.toUpperCase()));
  return _ar;
}

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

I would like to know if there are any one liners that can do this too : same operation on elements of subarrays

Answer

Strings are immutable in JavaScript and it is not an array of characters.

const str = "Test";

str[0] = "K";

console.log(str);

It won’t change the string as you can see in the above example.

When we use bracket notation for character access, we cannot delete or assign a new value. If we do, it silently fails. mdn

So we need to assign a new string with the uppercase first character and rest as it is.

What you can also do is. Split array into a character array and uppercase the first character and join them. But here still we are creating a new array with split and after joining the array we get the new string.

let str = "test string";

str = str.split("");
str[0] = str[0].toUpperCase();
str = str.join("");
console.log(str);

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *