5

I am trying to make a javascript program that takes a string and capitalizes the first letter of every word and makes every other character lowercase.

function titleCase(str) {
  str = str.toLowerCase();
  var array = str.split(" ");
  for(var i =0; i< array.length ; i++){
    array[i][0] = array[i].charAt(0).toUpperCase();

  } 
  var finalString = array.join(" ")
  return finalString ; 
}

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

For some reason array[i].charAt(0).toUpperCase(); won't pass it's value to array[i][0]. This ends up making it return the string with just all lowercase letters instead of having the first letter of each word being capitalized.

Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
vin42tau
  • 51
  • 1
  • 3

3 Answers3

3

Sounds like you want to do something more like this:

function titleCase(str) {
  str = str.toLowerCase();
  var array = str.split(" ");
  for(var i =0; i< array.length ; i++){
    //array[i] is an immutable string. So we need to rebuild it instead.
    array[i] = array[i].charAt(0).toUpperCase() + array[i].substring(1);
  } 
  var finalString = array.join(" ")
  return finalString; 
}

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

Strings can be read as char arrays using bracket notation. However, you cannot change a particular character that way since strings are not mutable objects.

CollinD
  • 7,304
  • 2
  • 22
  • 45
3

JavaScript strings are immutable, so you cannot actually change individual characters by indexing them using the [] operator. Here is a fixed version that uses substring to build the final string instead:

Live Demo:

function titleCase(str) {
  str = str.toLowerCase();
  var array = str.split(" ");
  for(var i =0; i< array.length ; i++){
    array[i] = array[i].charAt(0).toUpperCase() + array[i].substring(1);

  } 
   var finalString = array.join(" ")
  return finalString ; 
}

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

JSFiddle Version: https://jsfiddle.net/rakdtpbb/

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
0

The toUpperCase() method returns the value of the string converted to uppercase, but does not affect the value of the string itself.

Anders
  • 8,307
  • 9
  • 56
  • 88
Stella
  • 139
  • 3
  • 14