Capitalize the First Letter of Each Word in Array in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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.slice(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 lowercased 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 argument we passed to the String.slice method is the start index - the index of the first character to be included in the string.

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

We know that the index of the first character in the string is 0, so we pass 1 as a parameter to the slice() method.

Our function doesn't change the contents of the original array. It returns a new array.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.