Capitalizing the first letter of a word with javascript

I have been learning javascript for about a month now and I will say it is a fun experience but sometimes it gets very difficult to understand how certain concepts work, especially when it comes to inbuilt functions and methods. I am currently learning javascript from freecodecamp and I recently completed their basic algorithm scripting exercises, which are basically just problems I had to solve using javascript, and I am going to talk about one of them which was very challenging for me.

Title case a sentence

Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lowercase.
For the purpose of this exercise, you should also capitalize connecting words like “the” and “of”.

titleCase("I'm a little tea pot") should return the string I'm A Little Tea Pot.
titleCase("sHoRt AnD sToUt") should return the string Short And Stout.

Provided code:

function titleCase(str) {
  return str;
}

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

The solution

At first I thought there was a function that can capitalize a word just like we have in python, where I can just do something like string.capitalize() and it will return a copy of the string with the first letter capitalized while the others are in lower case. The plan was to loop through each word in the sentence and capitalize them but that would have been possible in python, not in javascript (or maybe I don’t know a function or method that can do that).

The only thing I was left with was the .toUpperCase() method but that will just turn the whole string to uppercase, which means I have to find a way to isolate the first letter of each word in a sentence and then convert them to uppercase. To isolate each letter of a word, won’t it be easier if will split up the string into individual words? And that’s exactly what I did.

function titleCase(str) {
    let splitted = str.split(" ");
    let updated = [];
}

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

The split() method simply split the string into substrings and it does that by splitting them where there’s a white space, that’s why I added a string with just a single white space between those brackets (“ “). If you were to do something like str.split(), it will just return an array of the whole string back to you, it will be [ "I'm a little tea pot" ] and that isn’t what we want. But using a whitespace as a separator, the returned string will now be [ "I'm", 'a', 'little', 'tea', 'pot' ].

I also created a new array called updated which is empty for now and it’s where we are going to add the updated words after we have capitalized each of them. Now that we have separated the string into individual array items, it will be easier to loop through them and capitalize their first letter. And to do that, we are going to use a for loop

for (let i = 0; i < splitted.length; i++) {
      updated[i] = splitted[i][0].toUpperCase() + splitted[i].slice(1).toLowerCase();
    }

Code explanation

The code will run from 0 to less than the length of splitted array (which is 5). So, i will run from 0 to 4.

splitted[i][0]: splitted is the array that contains the splitted string. I am simply accessing each of those array items which are just words and in each word, I am accessing their first letter, that’s the essence of the [0].

splitter[i]splitted[i][0]
splitted[0] = I’msplitted[0][0] = I
splitted[1] = asplitted[1][0] = a
splitted[2] = littlesplitted[2][0] = l
splitted[3] = teasplitted[3][0] = t
splitted[4] = potsplitted[4][0] = p

toUpperCase(): This part doesn’t need much explanation because it’s quite obvious what its function is but just in case it isn’t clear, this method will convert the letters to uppercase. Now that we have successfully isolated the first letter of each word, this method will simply turn them to uppercase on each iteration.

+ splitted[i].slice(1): After capitalizing the first letters of each word, we can’t simply throw away the remaining part of the word, which means we have to concatenate them back to the first letter but before we do that, we first have to remove the previous first letters which aren’t capitalized. The toUpperCase() method doesn’t modify the original string, which means that the splitted array will still contain the lowercase form of each word. If we don’t remove the previous first letters, we are going to end up with something like this:

[ "II'm", 'Aa', 'Llittle', 'Ttea', 'Ppot' ]

The first letter of each word is now capitalized but we still have the previous lowercase letter there and now the whole sentence doesn’t even make any sense. We can remove the previous letters with the slice() method

slice(1): This method simply copies the given number of elements from one array to another array. It usually takes 2 parameters: slice(start, end). Start is the index where it will start copying from while end is the index where it will stop, but it won’t include that particular index. So, slice(0, 4) will copy from index 0 to index 3, it won’t include index 4. But what happens when we provide just one parameter? It will simply start copying from the provided index until the end of the array. So, slice(1) will simply start copying from index 1 until the end of the array.
With this method, we will start copying from the second letter of each word and ignore each first letter.

A little detour

At this point, I thought I was done and after adding the remaining part of the code, I tested it with titleCase("I'm a little tea pot") and the result was I'm A Little Tea Pot which is the correct answer but when I tried submitting, I failed some of the tests provided and one of them is titleCase("sHoRt AnD sToUt"). It was supposed to return Short And Stout but instead, my solution returned SHoRt AnD SToUt. The last part of the question said I should “Make sure the rest of the word is in lower case” and I easily fixed that with:

toLowerCase(): This function will convert the words I copied with the slice() method to lowercase.

And now the code is done but there was still one problem; I was supposed to return a string as the answer but instead what I got was an array; [ "I'm", 'A', 'Little', 'Tea', 'Pot' ], I didn’t know how to convert the array back to a string. I did a quick google search on how to covert an array to a string (that was how I learned how to convert a string to an array in the first place) and I got the answer I needed:

str = updated.join(" ")

The join() method is the opposite of the split() method; where the split() method splits a string into an array, the join() method joins elements of an array into a single string. The words will be joined and separated with a space, that’s why I used (“ “). If I had just used only split(), then I would have ended up with: I'm,A,Little,Tea,Pot.

This is what the entire code now looks like:

function titleCase(str) {
    let splitted = str.split(" ");
    let updated = [];
    for (let i = 0; i < splitted.length; i++) {
      updated[i] = splitted[i][0].toUpperCase() + splitted[i].slice(1).toLowerCase()
    }
    str = updated.join()
    return str;
  }
  
  let result = titleCase("I'm a little tea pot");
  console.log(result)

With the above code, I successfully passed all the provided tests including peculiar ones like titleCase("sHoRt AnD sToUt"). This problem was very challenging for me because I never knew about the split() and join() methods but I was able to learn them when the need came up. In the end, I learned a lot from the problem and it actually turned out to be fun. There are 16 total problems in the basic algorithm scripting section of freecodecamp JavaScript course and some were simple while others were even more difficult than this one, but I completed all of them and now I am learning JavaScript DOM which I will say is the fun side of JavaScript.

Thanks for reading

Connect with me on:
Twitter: @kushyzeena
Readcash: @kushyzee

Lead image: Image by rawpixel.com on Freepik
Edited with Canva


0
0
0.000
9 comments
avatar

This is such a nice explanation of the basic syntaxes of JavaScript. I haven't used it yet since I'm learning Python and Java at the same time. Our university required us to do so. It's a bit tiring, but, um, it's bearable. Looking forward to more of your JavaScript's blogs.

0
0
0.000
avatar

I had to learn C and python first before learning JavaScript and it makes it easier to grasp JavaScript concepts. Learning python and Java will make your transition to JavaScript very easy when you eventually decide to learn it

0
0
0.000
avatar
Thank you for sharing this post on HIVE!

Your content got selected by our fellow curator tibfox & you received a little thank you upvote from our non-profit curation initiative. Your post will be featured in one of our recurring curation compilations which is aiming to offer you a stage to widen your audience within the DIY scene of Hive.

Next time make sure to post / cross-post your creation within the DIYHub community on HIVE and you will receive a higher upvote!

Stay creative & hive on!
0
0
0.000
avatar

It is indeed detailed. I think I'm a little bit rusty in this aspect I may have to refine myself on their website.. Thanks for sharing

0
0
0.000
avatar

I think all programmers at one point become rusty if they haven't used a particular language (or a certain aspect of it) for a long time, it happens to me too. Thank you for reading

0
0
0.000
avatar

I don't know why but I really enjoy solving programming problems like this once in a while. It feels good sometimes to practice fundamentals. Also, after reading this post, I think it may be finally time for me to start learning JavaScript. I learnt Python and C++, and this looks like a combination of the two. I'm looking forward to more of your creations with JavaScript.

0
0
0.000
avatar

Exactly, JavaScript draws most of its syntax from C and python, it will be very easy to transition to it if you already know C++ and python. Thank you for stopping by

0
0
0.000