Capitalizing Words in Javascript

1e4_

Ian

Posted on January 18, 2021

Capitalizing Words in Javascript

I was looking for a solution on capitalizing all words in a string in Javascript this morning to use as the title of a page, I found a bunch of solutions, some included regex, some included looping through every character, some required a whole function.

I wanted something much cleaner and thought I'd share with everyone my solution

For this example I will be using the string "my awesome title"

"my awesome title".split(' ').map(i => {
    return i[0].toUpperCase() + i.substr(1);
}).join(' ');
Enter fullscreen mode Exit fullscreen mode

So what is happening? First we split the string into an array by a space, we then iterate over it returning the first character of the string as uppercase, and the rest of the string starting at position 1. We then join it all back together with a space.

You can easily turn this into a function

capitalizeWords(words) {
    return words.split(' ').map(i => {
        return i[0].toUpperCase() + i.substr(1);
    }).join(' ');
}
Enter fullscreen mode Exit fullscreen mode

Or if you are writing in VueJS like I needed to you can created a computed property, you will need to change the this.$route.params.category to what you want and split it by the appropriate character, for my requirement it was split by a dash

computed: {
    title: () => {
        this.$route.params.category.split('-').map((i) => {
            return i[0].toUpperCase() + i.substr(1)
        }).join(' ')
    }
}
Enter fullscreen mode Exit fullscreen mode

There seems to be quite a few ways to do this, but I found this way to be cleaner than requiring regex, if you want to do it with regex, I found this blog had an example

💖 💪 🙅 🚩
1e4_
Ian

Posted on January 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related