How to make the first letters title in JavaScript

Learn how to capitalize the first letter of each word in a string using JavaScript, with an example.

Making the First Letters Title in JavaScript

In order to make the first letters of each word in a string title-cased in JavaScript, you can use the toUpperCase() method. To use this method, you must first select the string that you would like to title-case. An example of this is shown below:


var str = "make the first letters title";

Once you have the string, you can use the toUpperCase() method to make the first letter of each word in your string title-cased. This is done by looping through the string and checking to see if the current character is the first letter of a word. If it is, then you can use the toUpperCase() method on that character. An example of this can be seen below:


var str = "make the first letters title";
var result = "";

for(var i = 0; i < str.length; i++){
  if(i === 0 || str[i-1] === ' '){
    result += str[i].toUpperCase();
  } else {
    result += str[i];
  }
}

console.log(result); // Outputs: "Make The First Letters Title"

In the above example, we loop through the string and check to see if the current character is the first letter of a word. If it is, then we use the toUpperCase() method on that character. Otherwise, we just add the character to the result string. Finally, we log the result to the console which should be the string in title-case.

In this way, you can use the toUpperCase() method in JavaScript to make the first letters of each word in a string title-cased.

Answers (0)