Capitalize Words In JS

Here’s a function that takes a string as input and returns a new string with every word’s first letter capitalized:


function capitalizeEveryWord(str) {
  // Split the string into an array of words
  const words = str.split(' ');

  // Loop through the array of words
  for (let i = 0; i < words.length; i++) {
    // Capitalize the first letter of the current word
    words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);

  // Join the array of words back into a single string
  return words.join(' ');

For example:

capitalizeEveryWord('hello world'); // returns "Hello World"


Leave a Reply

Your email address will not be published. Required fields are marked *