Borislav Hadzhiev
Fri Oct 22 2021·2 min read
Photo by Sebastian Pichler
To capitalize the first letter of each word in an array:
map()
method to iterate over the array.toUpperCase()
method on the first character of
the word and concatenate the rest.map
method will return a new array with all words capitalized.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.
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.
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.