How to Use Title Case in JavaScript (W3Schools Tutorial)?

Estimated read time 1 min read

To convert a string to title case in JavaScript, you can write a function that splits the string into words, capitalizes the first letter of each word, and then rejoins the words back together. Here’s an example:

function toTitleCase(str) {
  return str.toLowerCase().split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
}

let myString = "hello world";
let titleCased = toTitleCase(myString);
console.log(titleCased); // "Hello World"

In this example, the toTitleCase function takes a string as an argument, and performs the following steps:

  1. Uses the toLowerCase() method to convert the string to all lowercase letters.
  2. Uses the split() method to split the string into an array of words, separated by spaces.
  3. Uses the map() method to iterate over the array of words, capitalizing the first letter of each word using the toUpperCase() method.
  4. Uses the join() method to join the capitalized words back together into a single string, separated by spaces.

The result is a string in title case, with the first letter of each word capitalized. Note that this approach assumes that words are separated by spaces. If your string uses a different separator, you will need to modify the split() method accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply