Capitalizing a string in JavaScript.

In this blog I’m going to help you understand how to capitalize a string in JavaScript. Let’s get started! So the algorithm is simple, we have a function that accepts a string, and that function should capitalize the first letter of each word in the string, and then return the entire string. Sounds simple, right? Well let’s start off with writing out our function. We also want to have an empty array at the top of our function so that we can store what’s later going to be our results, we can just simply call that variable wordsArr and set that to an empty array. So far our code should look like this:

Capitalize function.

After we’ve done so, we want to start a for loop for the string that was provided to use through the argument of the function. We would also use the .split(“ “) method to split by the space character to get an array of words so that we can iterate over each word. Our code should look similar to this right now:

Iterating over each word in the string.

Now here is where most of the logic starts to come in. So we want to grab the first letter of our word, and we will like to capitalize it. To do so, we would write out “word[0].toUpperCase()” and we would also like to add that capitalized letter to the rest of our word. We want to grab everything after the first letter of the word, and to do so, we would write out “word.slice(1)”, and guess what we do after? We add them together! It should look like this: “word[0].toUpperCase() + word.slice(1)”. Remember our empty array at the top of our function? We need to push those results into that empty array! After pushing it, our code is going to look like this:

Pushing our results into wordsArr.

After we’re done iterating throughout our string we now have our wordsArr that’s been populated by the results of iterating throughout the string. After that, we want to join our words together with a space character such as: “wordsArr.join(“ ”), and after that, we just simply return our wordsArr. After all of that has been done, your code should look like this:

Final results of the function.

I hope this blog has helped you out with understanding how to capitalize a sentence or word. Thanks for reading!