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:
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.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.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:
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:
I hope this blog has helped you out with understanding how to capitalize a sentence or word. Thanks for reading!