Bonfire: Title Case a Sentence Solution

Today we’re going to capitalize the first letter in each word of a sentence. The Bonfire calls this one the Title Case a Sentence exercise. Like always, we’ll start this one off by visualizing it without code–basically writing pseudo code to lay out the steps for how we’re going to approach this problem.

Approaching the Problem

The Bonfire starts you off with this:

function titleCase(str) {
  return str;
}

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

It is all very familiar at this point. You’re looking to make each letter in the sentence that is at the start of the word an uppercase letter instead of its lowercase variant. Here’s how I imagine breaking this down:

  1. I want the first character of every word to be capitalized, but I can’t modify the string. So one of the first things I want to do is split the sentence into an array of words. The array can tell when to make a new array item based on the spaces between each word in the sentence. I can probably use split() for this.
  2. Next thing I want to do is check each of the items in my array and detect the first character of every item. That character will then be set to uppercase. I can use .toUpperCase() for this.
  3. And since I can’t return an array that will validate because the Bonfire expects a string, I’ll have to join all the items in the array back into a string. I’ll use join() for this.
  4. Now, I know Bonfire is going to doublecheck my answers not just on the string it gives me in the provided code, but I’ll probably have to worry about what happens when all the characters in the string are uppercase or there’s alternate case situations too. I might have to figure out a way to target all the characters after the first one and force all those to be lower case using toLowerCase().

I know some of the above methods because we’ve used most of them before. We’ve used split() and join() together to deal with strings and manipulating them. And we’ve used toLowerCase() as well. The only one in the above process that’s new is toUpperCase(). And if you already know a method called toLowerCase() exists, you can be pretty sure that its opposite also exists for use. Let’s go ahead and start writing this out.

The For Loop Solution

The for loop solution is probably the one that requires the least amount of code that I could come up with. I’m going to combine two methods in my initial approach to save on some space and the two methods I’m combining are split() and toLowerCase(). Anytime I can kill two birds with one stone when it comes to typing code, I take it. The less code there is, the less chances I have of screwing something up. Here’s what I got:

function titleCase(str) {
  var titleStr = str.split(' ');
  
  return titleStr;
}

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

I created a local variable called titleStr to work with inside of the titleCase() function. titleStr becomes str while it is being worked on inside the function. Then I split the string into arrays and load the array up by the word using the space between each word as a marker to split each array item. So, the array I end up with looks like this:

(I’m, a, little, tea, pot)

Now we’re going to write our for loop to locate the first character of each array item and replace it with an uppercase character using toUpperCase(). Here’s what I got:

function titleCase(str) {
    var titleStr = str.split(' ');
    for (var i = 0; i < titleStr.length; i++) {
        titleStr[i] = titleStr[i].charAt(0).toUpperCase();
    }
    return titleStr.join(' ');
}
titleCase("I'm a little tea pot");

We’re starting off with a for loop that iterates through the titleStr array that contains all the words of our original string. As we loop through the array, we’re checking for the first character of each word. In the for loop, each word is represented with titleStr[i] and charAt(0) locates the first position of each of those words. Once it locates the first character in a word within the array, it changes the character to uppercase using toUpperCase(). Then we return titleStr as a string by using join() to put the array of words back into a normal string.

So this is a good start, but we’re not done yet. Not content with keeping this simple, the Bonfire will check us against strings such as hONEY, i’M hOME or WELCOME TO DISNEYLAND. They’re doing this so we don’t just call toUpperCase() on the string and call it a day. So, we really do need to address not only the first character in each word, but the rest of the word as well. To do this, I’m going to introduce a new method we haven’t worked with before called slice().

A Bit About Slice()

Slice is a method used on arrays to return a portion of a sequence, within slice we can specify a value that is a negative or positive integer. If no value is specified, it will assume 0 by default.

Slice also takes in more than one integer and can be used to specify a range. So if you wanted to, let’s say select the second to sixth within a sequence, you would specify something like this: .slice(1,5). Where one is the second item in the array, and five is the sixth. This will make slice select all within that range up to the fifth element (2, 3, 4, 5).

Slice() also takes negative values which will typically begin at the end of an sequence. So declaring .slice(3, -1) means it will select the fourth item to the second last item within the sequence.

Finally, if you don’t specify a second value, slice() will start selecting where you specified the first value and continue selecting until it hits the end of the sequence. In this Bonfire, we’re going to use slice() to select starting at the second character in our words and continue through the end of each word. So for example, in the word “bird”, we would be declaring, .slice(1) which would select the bold portions of the word: bird.

Finishing the For Loop Solution

Here’s the code with slice in place. Notice that we’re adding another pass to our code that addresses the rest of the word. Slice() starts looking at the word at position 1 (or the second character) and proceeds to set all subsequent characters to lower case using toLowerCase(). All this is still being done in the same basic for loop we started before. Here’s the final code:

function titleCase(str) {
    var titleStr = str.split(' ');

    for (var i = 0; i < titleStr.length; i++) {

        titleStr[i] = titleStr[i].charAt(0).toUpperCase() + titleStr[i].slice(1).toLowerCase();

    }

    return titleStr.join(' ');
}

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

Run that through and it’ll validate.

Resources

MDN Array.prototype.slice()
Goes over Slice() and how it works, plus includes handy examples.


Posted

in

by

Comments

7 responses to “Bonfire: Title Case a Sentence Solution”

  1. Creative Othman

    this is really helpful

    1. Thanks for leaving a comment, Creative Othman. I’m glad this was useful for you. 🙂

  2. Gabriel Lang

    Hey Thanks for the help! sometimes some of these challenges just leave me directionless on where to start! So to have detailed explanations as to why the code is working the way it does is so very helpful!

    1. No problem! Glad I could help. 🙂

  3. Robert Hill

    I really enjoy your solutions and explanations. Thank you so much for your all your hard work!!!
    You definitely make learning javascript easier to understand.

    1. Thank for coming by and leaving such a nice comment, Robert! I’m glad my write ups have been helpful. 🙂