1

I want to be able to change the first letter of certain words in a string, specifically because I want to capitalise the first and last name of 'john doe'. I have written this code:

let name = 'john doe';
name = name.split(' ');
name[0][0] = name[0][0].toUpperCase();
name[1][0] = name[1][0].toUpperCase();
console.log(name.join(' '));

However, my code does not execute any change whatsoever.

Output:
> "john doe"

Expected output:
> "John Doe"

I was wondering what the problem was so I removed toUpperCase() and logged each step.

let name = 'john doe';
name = name.split(' ');
console.log(name);
console.log(name[0][0]);
name[0][0] = 'p';
console.log(name[0][0]);

The output shows that the string was successfully converted into an array. It shows that name[0][0] does indeed hold the value 'j'. But it does not change to 'p'.

Output: 
> "Array ["john", "doe"]"
> "j"
> "j"

Expected output:
> "Array ["john", "doe"]"
> "j"
> "p"

I see no reason why this should not work.

Gerard Way
  • 91
  • 9

1 Answers1

0

Strings are immutable. That means that the chars are readonly, trying to set them does actually nothing:

 let str = "123";
 str[0] = "2";
 console.log(str); // "123"

To modify them, you have to build up a new string composed of the previous string's characters:

str = "2" + str.slice(1);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151