Javascript Capitalize First Letter in Every Word Problem

In this problem, I am taking in a string and capitalizing the first letter of every word.  Here I use a for…of loop.  First I use the split() method to convert the string into an array and take the first letter of every word and capitalize it.  Then I use the slice() method to add back the rest of the word.  Slice(1) will take characters starting at index 1 and everything after it.

// OPTION 1
function capitalize(str) {

   capsArray = [];

   for (let word of str.split(' ')) {
      capsArray.push(word[0].toUpperCase() + word.slice(1));
   }
   return capsArray.join(" ");
};

const output = capitalize("hello how are you");
console.log(output);

Option 2 – In this case, I work with the string as a string.  I look to see if the character to the left is a space.  If so, I make the character a capital letter.  For the very first letter we are not able to look left, so I make it capital by default (“let result = str[0].toUpperCase()” ).  Then I loop through the rest of the string, adding the characters back one-by-one and capitalizing them if the character to the left is a space.

// OPTION 2
function capitalize(str) {
   let result = str[0].toUpperCase();

   for (let i=1; i<str.length; i++) {
      if(str[i-1] === ' ') {
         result += str[i].toUpperCase();
      } else {
         result += str[i];
      }
   }
   return result;
}

const output = capitalize("hello how are you");
console.log(output);

 

Leave a Reply