Capitalize the First Letter of Each Word in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

Capitalize the First Letter of Each Word #

To capitalize the first letter of each word in a string:

  1. Call the split() method on the string to get an array containing the words in the string.
  2. Call the map() method to iterate over the array and capitalize the first character of each word.
  3. Join the array of words into a string, using the join() method.
index.js
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.

If you don't want to lowercase all non-first letters in a word, remove the call to the toLowerCase() method.

We used the the String.split method on the string and split it on each space. This returns an array containing the words in the string.

index.js
// ๐Ÿ‘‡๏ธ ['Hello', 'world'] console.log('Hello world'.split(' '));

The next step is to call the Array.map method on the array of words.

The function we passed to the map method gets called with each element (word) in the array.

In the function, we access the first character of each word, convert it to uppercase and concatenate it to the rest of the string.

index.js
// ๐Ÿ‘‡๏ธ ['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.

index.js
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'));

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee