How to Capitalize the First Letter of Each Word in an Array in JavaScript
To capitalize the first letter of each word in an array in JavaScript:
- Iterate over the words array with
.map()
. - For each word, return a new word, the uppercased form of the word's first letter added to the rest of the word.
For example:
function capitalizeWords(arr) {
return arr.map((word) => {
const capitalizedFirst = word.charAt(0).toUpperCase();
const rest = word.slice(1).toLowerCase();
return capitalizedFirst + rest;
});
}
const words = ['welcome', 'to', 'CODING', 'Beauty'];
// [ 'Welcome', 'To', 'Coding', 'Beauty' ]
console.log(capitalizeWords(words));
Our capitalizeWords()
function takes an array of words and returns a new array with all the words capitalized, without mutating the original array.
Firstly, we call the map()
method on the array, passing a callback function as an argument. This function will be called and return a result for each word in the array.
In the callback, we get the word's first character with charAt()
, convert it to uppercase with toUpperCase()
, and concatenate it with the rest of the string.
We use the String
slice()
method to get the remaining part of the string. Passing 1
to slice()
makes it return the portion of the string from the second character to the end.
Note: String (and array) indexing is zero-based JavaScript, so the first character in a string is at index 0, the second at 1, and the last at str.length-1
After capitalizing the word, we lowercase it with the String
toLowerCase()
method. You can remove this toLowerCase()
call if it's not necessary for the non-first letter of each word in the array to be capitalized.
See also
- How to Remove All Classes From an Element With JavaScript
- How to Convert XML to JSON in JavaScript
- How to Subtract 6 Months From a Date in JavaScript
- How to Detect a Browser or Tab Close Event in JavaScript
- How to Fix the "Cannot read property '0' of undefined" Error in JavaScript
- How to Fix the "structuredClone is not defined" Error in Node.js