Capitalize the First Letter of Each Word in Array in JS

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

Capitalize the First Letter of Each Word in Array #

To capitalize the first letter of each word in an array:

  1. Use the map() method to iterate over the array.
  2. On each iteration, use the toUpperCase() method on the first character of the word and concatenate the rest.
  3. The map method will return a new array with all words capitalized.
index.js
function capitalizeWords(arr) { return arr.map(element => { return element.charAt(0).toUpperCase() + element.substring(1).toLowerCase(); }); } // ๐Ÿ‘‡๏ธ ['Hello', 'World'] console.log(capitalizeWords(['hello', 'world'])); // ๐Ÿ‘‡๏ธ ['One', 'Two', 'Three'] console.log(capitalizeWords(['one', 'two', 'three']));

We created a reusable function that capitalizes the first letter of each array element.

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

On each iteration, we access the character at index 0 and convert it to uppercase, using the String.toUpperCase method.

The last step is to take the rest of the string and add it to the capitalized first character.

We lowercase the rest of the string to make sure it doesn't contain any uppercase characters after the first one. If you don't want to lowercase the rest of the string, remove the call to the toLowerCase method.

The only parameter we passed to the String.substring method is the start index - the index at which we start extraction of characters.

Indexes are zero-based in JavaScript. The index of the first character in a string is 0 and the index of the last - str.length - 1.

Because we know that the index of the first character in the string is 0, we pass 1 as a parameter to the substring method.

Our function does not change the contents of the original array. It returns a new array instead.

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