Capitalize the First Letter of Each Word in Array in JS

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
6 min

banner

# Table of Contents

  1. Capitalize the First Letter of Each Word in an Array
  2. Capitalize the First Letter of Each Word in a String

# Capitalize the First Letter of Each Word in an Array

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

  1. Use the Array.map() method to iterate over the array.
  2. Use the toUpperCase() method to capitalize the first letter of each element.
  3. Use the slice() method to append the rest of the string to the result.
index.js
function capitalizeWords(arr) { return arr.map(word => { const firstLetter = word.charAt(0).toUpperCase(); const rest = word.slice(1).toLowerCase(); return firstLetter + rest; }); } // ๐Ÿ‘‡๏ธ [ 'Bobby', 'Hadz' ] console.log(capitalizeWords(['bobby', 'hadz'])); // ๐Ÿ‘‡๏ธ [ 'Bobby', 'Hadz', 'Com' ] console.log(capitalizeWords(['bobby', 'hadz', 'com']));

capitalize first letter of each word in array

The code for this article is available on GitHub

The capitalizeWords function takes an array and 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.

The map() method returns a new array containing the values returned from the callback function.

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

index.js
console.log('bobby'.charAt(0)); // ๐Ÿ‘‰๏ธ b console.log('bobby'.charAt(0).toUpperCase()); // ๐Ÿ‘‰๏ธ B

The String.charAt() method returns the character at the specified index.

If the index doesn't exist in the string, the method returns an empty string.

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

index.js
// ๐Ÿ‘‡๏ธ Bobby console.log(str.charAt(0).toUpperCase() + str.slice(1).toLowerCase());

We used the String.toLowerCase() method to convert the rest of the string to lowercase.

Calling the method is not necessary if you don't want to have the rest of the string lowercased.

The String.slice method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe index of the first character to exclude from the returned substring

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

We used an argument of 1 for the start index to start the slice at the second character of the string.

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

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

Alternatively, you can use the Array.forEach() method.

# Capitalize the First Letter of Each Word in Array using forEach()

This is a three-step process:

  1. Use the Array.forEach() method to iterate over the array.
  2. Use the toUpperCase() method to uppercase the first letter of each word.
  3. Update the array element at the current index.
index.js
const arr = ['bobby', 'hadz', 'com']; arr.forEach((word, index) => { const firstLetter = word.charAt(0).toUpperCase(); const rest = word.slice(1).toLowerCase(); arr[index] = firstLetter + rest; }); // ๐Ÿ‘‡๏ธ [ 'Bobby', 'Hadz', 'Com' ] console.log(arr);

capitalize first letter of each word in array using foreach

The code for this article is available on GitHub

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

The forEach() method returns undefined, so we have to perform some kind of mutation to persist the state.

On each iteration, we use the toUpperCase() method to convert the first letter of the current word to uppercase and the slice() method to get the remainder of the word.

The last step is to use the index to update the current array element.

You can also use a basic for loop to achieve the same result.

# Capitalize the First Letter of Each Word in Array using for

This is a three-step process:

  1. Use a for loop to iterate over the array.
  2. Use the toUpperCase() method to uppercase the first letter of each word.
  3. Update the array element at the current index.
index.js
const arr = ['bobby', 'hadz', 'com']; for (let index = 0; index < arr.length; index++) { const firstLetter = arr[index].charAt(0).toUpperCase(); const rest = arr[index].slice(1).toLowerCase(); arr[index] = firstLetter + rest; } // ๐Ÿ‘‡๏ธ [ 'Bobby', 'Hadz', 'Com' ] console.log(arr);

capitalize first letter of each word in array using for loop

The code for this article is available on GitHub

We used a basic for loop to iterate over the array of words.

On each iteration, we uppercase the letter at index 0, convert the rest of the word to lowercase and append the two strings.

Which approach you pick is a matter of personal preference. I'd use the Array.map() method as I find it quite direct and intuitive.

# Capitalize the First Letter of Each Word in a String

To capitalize the first letter of each word in a string:

  1. Use the split() method to split the string into an array of words.
  2. Use the Array.map() method to iterate over the array.
  3. Use the join() method to join the array into a string.
index.js
function toTitleCase(str) { const titleCase = str .toLowerCase() .split(' ') .map(word => { return word.charAt(0).toUpperCase() + word.slice(1); }) .join(' '); return titleCase; } // ๐Ÿ‘‡๏ธ Bobby Hadz console.log(toTitleCase('bobby hadz')); // ๐Ÿ‘‡๏ธ Hello World console.log(toTitleCase('hello world')); // ๐Ÿ‘‡๏ธ '' console.log(toTitleCase(''));

capitalize first letter of each word in string

The code for this article is available on GitHub

We created a reusable function that capitalizes the first letter of each word in a string.

We first convert the entire string to lowercase to make sure only the first letter in each word is uppercased.

If you don't want to lowercase all non-first letters in a word, remove the call to the toLowerCase() method.

We used the String.split() method to split the string into an array of words.

index.js
// ๐Ÿ‘‡๏ธ ['Hello', 'world'] console.log('Hello world'.split(' '));

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

The map() method returns a new array containing the values returned from the callback function.

In the function, we access the first character of each word, convert it to uppercase and concatenate it to the rest of the string.

index.js
// ๐Ÿ‘‡๏ธ ['Hello', 'World'] console.log( 'hello world'.split(' ').map(word => { return word.charAt(0).toUpperCase() + word.slice(1); }), );

At this point, we have an array containing the words in the string with the first letter of each word capitalized.

The last step is to use the Array.join() method to join the array into a string.

index.js
// ๐Ÿ‘‡๏ธ "Hello World" console.log( 'hello world' .split(' ') .map(word => { return word.charAt(0).toUpperCase() + word.slice(1); }) .join(' '), );

You can also use CSS to capitalize the first letter of each word.

# Capitalize the first letter of each word using CSS

To capitalize the first letter of each word using CSS:

  1. Select the element.
  2. Set the element's text-transform style to capitalize.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <p id="paragraph">bobby hadz com</p> <script type="module" src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const paragraph = document.getElementById('paragraph'); paragraph.style.textTransform = 'capitalize';

The p tag becomes Bobby Hadz Com after running the JavaScript code.

When the text-transform property is set to capitalize, the first letter of each word is uppercased.

The other characters in the string remain unchanged.

# Capitalize the first letter of each word using String.replace()

This is a three-step process:

  1. Use the String.replace() method with a regular expression.
  2. The regular expression should match the first letter of each word.
  3. Use the toUpperCase() method to convert the matches to uppercase.
index.js
function toTitleCase(str) { return str.replace(/(^\w|\s\w)/g, m => m.toUpperCase()); } // ๐Ÿ‘‡๏ธ Hello World console.log(toTitleCase('hello world')); // ๐Ÿ‘‡๏ธ Bobby Hadz Com console.log(toTitleCase('bobby hadz com'));
The code for this article is available on GitHub

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The String.replace() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Strings are immutable in JavaScript.

The forward slashes / / mark the beginning and end of the regular expression.

index.js
function toTitleCase(str) { return str.replace(/(^\w|\s\w)/g, m => m.toUpperCase()); }

The ^\w matches the first letter in the string.

The pipe | special character means OR, e.g. X|Y matches X or Y.

The \s\w part matches the first letter after a whitespace character.

We set the g flag because we want to match all occurrences of a first letter in a word and not just the first occurrence.

In its entirety, the regular expression matches the first letter of the string and the first letter of each word.

The second argument we passed to the replace() method is a function that gets called with each match.

We used the String.toUpperCase() method to convert each match (the first letter of each word) to uppercase.

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.

Copyright ยฉ 2024 Borislav Hadzhiev