JavaScript Function to Capitalize Words

  • Post category:JavaScript

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:

  1. The capitalizeWords function takes a string parameter representing the input sentence or string.

  2. The split(' ') method is used to split the string into an array of words. Each word is separated by a space character.

  3. We create an empty array called capitalizedWords to store the capitalized versions of each word.

  4. We iterate over each word in the words array using a for loop.

  5. For each word, we use the charAt(0) method to get the first character and toUpperCase() method to convert it to uppercase.

  6. We use the slice(1) method to extract the remaining characters of the word starting from the second character.

  7. We concatenate the capitalized first letter with the remaining characters to form the capitalized word.

  8. We push the capitalized word to the capitalizedWords array.

  9. Finally, we use the join(' ') method to join the capitalized words in the capitalizedWords array back into a single string, separated by spaces.

  10. 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.