Last updated: Mar 3, 2024
Reading timeยท6 min
To capitalize the first letter of each word in an array:
Array.map()
method to iterate over the array.toUpperCase()
method to capitalize the first letter of each
element.slice()
method to append the rest of the string to the result.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']));
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.
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.
// ๐๏ธ 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:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The 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.
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.
forEach()
This is a three-step process:
Array.forEach()
method to iterate over the array.toUpperCase()
method to uppercase the first letter of each word.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);
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.
for
This is a three-step process:
for
loop to iterate over the array.toUpperCase()
method to uppercase the first letter of each word.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);
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.
To capitalize the first letter of each word in a string:
split()
method to split the string into an array of words.Array.map()
method to iterate over the array.join()
method to join the array into a string.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(''));
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.
toLowerCase()
method.We used the String.split() method to split the string into an array of words.
// ๐๏ธ ['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.
// ๐๏ธ ['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.
// ๐๏ธ "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.
To capitalize the first letter of each word using CSS:
text-transform
style to capitalize
.Here is the HTML for the example.
<!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.
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.
String.replace()
This is a three-step process:
String.replace()
method with a regular expression.toUpperCase()
method to convert the matches to uppercase.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 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:
Name | Description |
---|---|
pattern | The pattern to look for in the string. Can be a string or a regular expression. |
replacement | A 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.
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.
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.