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(' ');
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(' ');
}
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(' ')
}
}
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
Top comments (4)
Nice one @ian .
I created a JavaScript Utility Library that comes with so many useful functions and method all categorized into modules. One of this modules is the "Str", which contains methods that manipulates a string. And amongst close to 40 methods, capitalizing a string is one of them.
You can check it out on Github
To achieve this using the library, after installation(obviously)
Great!
I've never found regex easy to understand especially at a glance