In JavaScript, we can capitalize the first letter of every word in a string easily with the help of a bunch of JavaScript String and Array methods. Here is our function to do this:

function capitalizeFirstLetter(str){
  var new_strings = str.split(" ");
  var new_string = [];
  for ( var i=0; i<new_strings.length; i++ ){
    new_strings[i] = new_strings[i].charAt(0).toUpperCase() + new_strings[i].substring(1);
  };
  new_string = new_strings.join(" ");
  return new_string;
};

Here would be a sample result using our function:

var someString = "this is a string with some words";

function capitalizeFirstLetter(str){
  var new_strings = str.split(" ");
  var new_string = [];
  for ( var i=0; i<new_strings.length; i++ ){
    new_strings[i] = new_strings[i].charAt(0).toUpperCase() + new_strings[i].substring(1);
  };
  new_string = new_strings.join(" ");
  return new_string;
};

console.log(capitalizeFirstLetter(someString))

#Output:
This Is A String With Some Words

When using string variables in JavaScript, we can easily perform string manipulation to change the value of the string variables.

One such manipulation is to capitalize the first letter of every word in a string.

We can easily capitalize the first letter of every word in JavaScript.

As seen in our function above, we first use the split() method to get an array of the strings from the string passed to the function. Then, we can loop over each word, and use the charAt() method to get the first character of the string and capitalize it with the toUpperCase() method. We then concatenate that back to the rest of the word with the help of the substring() method.

At the end, we can join the array of capitalized words back together with the join() method.

Below again is the function we created to capitalize the first letter of every word in a string.

function capitalizeFirstLetter(str){
  var new_strings = str.split(" ");
  var new_string = [];
  for ( var i=0; i<new_strings.length; i++ ){
    new_strings[i] = new_strings[i].charAt(0).toUpperCase() + new_strings[i].substring(1);
  };
  new_string = new_strings.join(" ");
  return new_string;
};

Hopefully this article has been helpful for you to learn how to use JavaScript to capitalize the first letter of every word in a string.

Find more here.

Categorized in:

JavaScript,

Last Update: May 3, 2024