Borislav Hadzhiev
Fri Oct 22 2021·2 min read
Photo by Carmen Marxuach
To capitalize the first letter of each word in a string:
split()
method on the string to get an array containing the words
in the string.map()
method to iterate over the array and capitalize the first
character of each word.join()
method.function getTitleCase(str) { const titleCase = str .toLowerCase() .split(' ') .map(word => { return word.charAt(0).toUpperCase() + word.slice(1); }) .join(' '); return titleCase; } // 👇️ Hello World console.log(getTitleCase('hello world')); // 👇️ Hello World console.log(getTitleCase('hello world')); // 👇️ '' console.log(getTitleCase(''));
We created a reusable function that capitalizes the first letter of each word in a string.
The first thing we do is lowercase the entire string to make sure that only the first letter of each word is uppercase.
toLowerCase()
method.We used the String.split method on the string and split it on each space. This returns an array containing the words in the string.
// 👇️ ['Hello', 'world'] console.log('Hello world'.split(' '));
The next step is to call the Array.map method on the array of words.
In the function, we access the first character of each word, convert it to uppercase and concatenate it to the rest of the string.
// 👇️ ['Hello', 'World'] console.log( 'hello world'.split(' ').map(word => { return word.charAt(0).toUpperCase() + word.slice(1); }), );
At this point, we have an array containing the words in the string with the first letter of each word being uppercase.
The final step is to join the array into a new string, using the Array.join method.
The join method takes a separator as a parameter. We split the string on a space and we have to join it on a space.
Here's the complete code snippet.
function getTitleCase(str) { const titleCase = str .toLowerCase() .split(' ') .map(word => { return word.charAt(0).toUpperCase() + word.slice(1); }) .join(' '); return titleCase; } // 👇️ One, Two, Three console.log(getTitleCase('one, two, three')); // 👇️ One Two console.log(getTitleCase('one two'));