We’ll discuss how to do it along with a couple of examples.
Let’s have a quick look at the following example.
As you can see, we’ve made the
Let’s understand how it works. Firstly, we’ve used the
Now, we just need to loop through all the elements of the array and capitalize the first letter of each element. Firstly, we’ve used the
Finally, we’ve used the
In this section, we’ll revise the aforementioned example with the
As you can see, it’s a single line function which allows you to do it much more easily. That's thanks to the
map method, which allows us to loop through array elements with much cleaner syntax. If you notice, we've used the
substring method in this version.
In the previous section, we saw how to capitalize the first letter of all words in a string. That isn't actually how a title should look, though. In title case, we only capitalize the first letter of major words, and we leave minor words lower case.
Here's a sample of how to apply the same Envato Tuts+ title-case rules that we use on all our posts.
As you can see, we've added a regular expression,
smallWords, to test whether a word is minor and should be left lowercase. We also created a simple function to check whether a word is at the beginning or end of the string, and whether it matches the small words list. Once again, we use the
map method to transform each word. This time, we're also making use of the
index parameter that
map makes available—this is how we find out whether the word is at the beginning or end of the string.
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.Update me weekly