How To Capitalize The First Letter Of Each Word In JS Array

Capitalize the First Letter of Each Word in JS Array

Hello guys, today we will introduce about how to capitalize the first letter of each word in JS array, there are many ways to do it like using the toUpperCase() method with map() method or using the toUpperCase() method with for loop. Follow this article to see how to do it.

Capitalize the first letter of each word in JS array

Using the toUppercase() method with map() method

The first way we want to introduce in this article is the toUppercase() method with map() method. We will use the map() method to iterate over the array. And using the toUppercase() method on the first letter of each word in the JS array. We already introduce the toUppercase() method in other article. You can read it here to get more information about this method.

Code example:

In this example, we call the map() method to iterate over the array and then use the charAt(0) with the toUppercase() method to capitalize the first letter in myArray. Connect remain letter of the element by using the substr() method.

var myArray = ["banana", "orange", "apple", "lemon"]
console.log("My array is: ", myArray)

// Calling the map() method with toUpperCase() and charAt() method
var newArray = myArray.map(a => a.charAt(0).toUpperCase() + a.substr(1));
console.log("After capitalizing the first letter of each word: ", newArray)

Output

My array is:  [ 'banana', 'orange', 'apple', 'lemon' ]
After capitalizing the first letter of each word:  [ 'Banana', 'Orange', 'Apple', 'Lemon' ]

Using the toUpperCase() method with for loop

The next way is using the toUpperCase() method with for loop.

  • We create the function to loop all elements in the array and call the toUpperCase() and charAt(0) to uppercase the first letter of the elements in myArray.
  • After that, we add the other letter of the element by using the substr() method.

Let’s see the example below to get more information.

Example:

var myArray = ["banana", "orange", "apple", "lemon"]
console.log("My array is: ", myArray)

// Using the for loop method with toUpperCase() and substr() method 
for (var i = 1; i < myArray.length; i++) {
	myArray[i] = myArray[i].charAt(0).toUpperCase() + myArray[i].substr(1);
}

console.log("After capitalizing the first letter of each word: ", myArray)

Output

My array is:  [ 'banana', 'orange', 'apple', 'lemon' ]
After capitalizing the first letter of each word:  [ 'banana', 'Orange', 'Apple', 'Lemon' ]

Summary

Hopefully, through the article, you have understood about how to capitalize the first letter of each word in JS array in different ways. However, we think using the toUpperCase() method with the map() method is better. What about your opinion, please leave a comment below!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *