- Split the string into an array of words with
- Iterate over the words array with
- For each word, return a new word that is an uppercase form of the word’s first letter added to the rest of the word.
- Join the words array into a string with
capitalizeWords() function takes a string and returns a new string with all the words capitalized.
First, we use the
toLowerCase() method to lowercase the entire string, ensuring that only the first letter of each word is uppercase.
// welcome to coding beauty console.log('WELCOME to coding beauty'.toLowerCase());
Tip: If it’s not necessary for the remaining letters in each word to be lowercase, you can remove the call to the
Then we call the
split() method on the string to split all the words into an array.
// [ 'welcome', 'to', 'coding', 'beauty' ] console.log('welcome to coding beauty'.split(' '));
After creating the array, we call the
map() method on it, with a callback function as an argument. This function will be called and return a result for each word in the array.
In the function, 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
slice() method to get the remaining part of the string. Passing
slice() makes it return the portion of the string from the second (index of 1) character to the end.
// [ 'Welcome', 'To', 'Coding', 'Beauty' ] console.log( 'welcome to coding beauty' .split(' ') .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) );
map() returns an array containing all the words in the string, with each word’s first letter capitalized.
Lastly, we concatenate all the words in a single string, with the
Passing a space (
' ') to
join() separates the words by a space in the resulting string.
// Welcome To Coding Beauty console.log(['Welcome', 'To', 'Coding', 'Beauty'].join(' '));
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.