How can I convert a string to title case in JavaScript?
Ava W
ava w profile pic

Converting a string to title case means capitalizing the first letter of each word while keeping the rest of the letters lowercase. Here's a step-by-step approach to achieving this in JavaScript: 1. Split the string into an array of words: - Use thesplit() method to divide the string into an array of individual words. Specify the separator as a space character' '.

1
2
3
4

   const string = 'convert string to title case';
   const words = string.split(' ');
   

In this example, the string'convert string to title case' is split into an array of words. 2. Capitalize the first letter of each word: - Iterate over the array of words and capitalize the first letter of each word while converting the remaining letters to lowercase. You can accomplish this by combining thetoUpperCase() andtoLowerCase() methods.

1
2
3
4
5

   for (let i = 0; i < words.length; i++) {
     words[i] = words[i][0].toUpperCase() + words[i].substring(1).toLowerCase();
   }
   

This loop iterates over each word in the array and modifies it to have the first letter capitalized usingtoUpperCase(). The remaining letters of each word are converted to lowercase usingtoLowerCase(). 3. Join the words back into a single string: - Use thejoin() method to combine the array of words back into a single string, using a space as the separator.

1
2
3

   const titleCaseString = words.join(' ');
   

Thejoin(' ') function joins the elements of thewords array using a space as the separator, resulting in a single title case string. Here's an example that demonstrates converting a string to title case:

1
2
3
4
5
6
7
8
9
10

const string = 'convert string to title case';
const words = string.split(' ');

for (let i = 0; i < words.length; i++) {
  words[i] = words[i][0].toUpperCase() + words[i].substring(1).toLowerCase();
}

const titleCaseString = words.join(' ');
console.log(titleCaseString); // Output: "Convert String To Title Case"

In this example, the string'convert string to title case' is split into individual words usingsplit(' '). The loop capitalizes the first letter of each word and converts the rest of the letters to lowercase. Finally, the modified words are joined back into a single string usingjoin(' '), resulting in the title case string"Convert String To Title Case". By following this approach, you can convert any string to title case in JavaScript. Remember to handle edge cases and consider additional rules for specific scenarios, such as handling abbreviations or special words that should remain in uppercase.