JavaScript provides several built-in string manipulation methods that allow you to manipulate and transform strings according to your requirements. One common requirement is capitalizing the first letter of each word in a sentence or string. In this tutorial, you will learn how to write a JavaScript function that accomplishes this task.
The capitalizeWords Function
The capitalizeWords
function takes an input string as a parameter and returns a new string where the first letter of each word is capitalized. Here’s the code for the function:
function capitalizeWords(string) {
const words = string.split(' ');
const capitalizedWords = [];
for (let i = 0; i < words.length; i++) {
const word = words[i];
const capitalizedWord = word.charAt(0).toUpperCase() + word.slice(1);
capitalizedWords.push(capitalizedWord);
}
const result = capitalizedWords.join(' ');
return result;
}
Explanation of the code:
- The
capitalizeWords
function takes astring
parameter representing the input sentence or string. - The
split(' ')
method is used to split thestring
into an array of words. Each word is separated by a space character. We create an empty array called
capitalizedWords
to store the capitalized versions of each word.We iterate over each word in the
words
array using afor
loop.For each word, we use the
charAt(0)
method to get the first character andtoUpperCase()
method to convert it to uppercase.We use the
slice(1)
method to extract the remaining characters of the word starting from the second character.We concatenate the capitalized first letter with the remaining characters to form the capitalized word.
We push the capitalized word to the
capitalizedWords
array.Finally, we use the
join(' ')
method to join the capitalized words in thecapitalizedWords
array back into a single string, separated by spaces.We return the result.
Example Usage
const inputString = "hello world";
const capitalizedString = capitalizeWords(inputString);
console.log(capitalizedString); // Output: "Hello World"
In this example, the input string is "hello world"
. After calling the capitalizeWords
function, the output is "Hello World"
.
Conclusion
In this tutorial, you learned how to write a JavaScript function that capitalizes the first letter of each word in a sentence or string. This can be useful when you need to display titles, headings, or any text where proper capitalization is required. By understanding the logic behind the capitalizeWords
function, you can apply similar concepts to solve other string manipulation tasks in JavaScript.