Write a function that accepts a string. The function should capitalize the first letter of each word in the string and return the result.
Examples:
capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'
To capitalize the first letter of each word in a string, you can break down the problem into these steps:
- Split the string into individual words.
- Capitalize the first letter of each word.
- Join the words back together into a single string.
Here’s a possible solution:
function capitalize(str) {
// Split the string into words
const words = str.split(' ');
// Capitalize the first letter of each word
const capitalizedWords = words.map(word => {
return word.charAt(0).toUpperCase() + word.slice(1);
});
// Join the capitalized words back into a single string
return capitalizedWords.join(' ');
}
// Test cases
console.log(capitalize('a short sentence')); // 'A Short Sentence'
console.log(capitalize('a lazy fox')); // 'A Lazy Fox'
console.log(capitalize('look, it is working!')); // 'Look, It Is Working!'
Explanation:
- The string is split into an array of words using the
split(' ')
method. - Each word is processed by the
map()
function:
charAt(0).toUpperCase()
converts the first letter to uppercase.slice(1)
gets the rest of the word starting from the second character.
The capitalized words are then joined back together with spaces using the join(' ')
method. This function will correctly capitalize the first letter of each word in the string.