FCC Bonfire Series 107: Title Case a Sentence

Strings and arrays, arrays and strings! We just can’t get enough of them. This time, we’ll be using the array and string methods we have used already, in order to write a function that takes a string (a sentence) and returns it in title case. An example of title case (the exercise explicitly states that connecting words -of, the, a- should also be capitalised for simplicity), would be the following:

‘hello there friends’ –> ‘Hello There Friends’

As you can see, we are but capitalising the first character for every word. And working on separate words screams of the split() method.

We are also going to be setting the whole string to lower case for normalisation purposes, we´ll then split, and iterate over every word, calling the toUpperCase() method on the first character. We will finally join the array back into a string and return it to the user.

function titleCase(str) {
  str = str.toLowerCase();
  str = str.split(' ');
  for (var i = 0; i < str.length; i++) {
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
  }
  return str.join(' ');
}

We are doing two new things here. Both of these things happen in the 5th line. First, we are using charAt(0) to select the character at index 0 (the first position) of the current word, and calling toUpperCase() on this character. Then, we are concatenating (+) the rest of the word, slice(1) will return every character in the word starting at index 1.

So in the end, we are just concatenating the capitalised first letter, and the rest of the word.

Code much, try hard and never forget to get some sleep!