There are a couple of methods in JavaScript that allow us to change the case of a string: toUpperCase()
and toLowerCase()
. Annoyingly, there isn't one to change a string to title case, so let's look at a helper function to do that instead:
/**
* Convert a string to title case
* {@link https://gist.github.com/kieranbarker/293b74f1b3b46272315d2e1719786b03}
* @param {String} str The string to convert
* @returns {String} The converted string
*/
function toTitleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
}
Please note: this is my adaptation of a function written by Sonya Moisset. All I did was rewrite it in my preferred style using the array map()
method instead of a for
loop. Credit to her! 🙏
The first thing we do is convert the string to lowercase and split it into an array of words. So if we passed in the string 'The lion, The witch and The wardrobe'
, we'd get back the array ['the', 'lion,', 'the', 'witch', 'and', 'the', 'wardrobe']
.
Then we use the map()
method to convert each word to title case. We take the first character of each word (word.charAt(0)
) and convert it to uppercase. Then we combine that with the rest of the characters, which gives us the word in title case. So if we take the word 'lion'
, we're doing 'L' + 'ion'
, which makes it 'Lion'
.
After our call to the map()
method, we have an array of words in title case: ['The', 'Lion,', 'The', 'Witch', 'And', 'The', 'Wardrobe']
. Now all we need to do is join the words back together; we can do this by calling join(' ')
, which will separate them with spaces once more.
The full process looks like this:
- Pass in string:
'The lion, The witch and The wardrobe'
- Convert to lowercase:
'the lion, the witch and the wardrobe'
- Split into array:
['the', 'lion,', 'the', 'witch', 'and', 'the', 'wardrobe']
- Map to title case:
['The', 'Lion,', 'The', 'Witch', 'And', 'The', 'Wardrobe']
- Join with spaces:
'The Lion, The Witch And The Wardrobe'