How to Convert String to Title Case with JavaScript

As a programmer, you might have encountered a scenario where you need to convert a string into a title case.

Title case is the format where each word in a sentence starts with a capital letter.

For instance, “how to convert string to title case with JavaScript” would become “How To Convert String To Title Case With JavaScript”.

In this tutorial, we will take a look at how to convert strings to title case using JavaScript.

This tutorial is designed for beginners who have just started coding with JavaScript and want to learn the basics of converting strings to title case.


Using the toLowerCase() and toUpperCase() methods

The toLowerCase() method is used to convert a string to lowercase, and the toUpperCase() method is used to convert a string to uppercase.

We can use these methods to convert a string to title case by converting the entire string to lowercase, and then converting the first letter of each word to uppercase.

Here is an example of how to use these methods to convert a string to title case:

function toTitleCase(str) {
  return str.toLowerCase().split(" ").map(function(word) {
    return word.charAt(0).toUpperCase() + word.slice(1);
  }).join(" ");
}

var str = "how to convert string to title case with JavaScript";
var result = toTitleCase(str);
console.log(result);
// Output: "How To Convert String To Title Case With JavaScript"

Using the replace() method

Another method to convert a string to title case is by using the replace() method.

The replace() method is used to replace a substring with a new substring.

We can use this method to convert a string to title case by replacing the first letter of each word with its uppercase equivalent.

Here is an example of how to use the replace() method to convert a string to title case:

function toTitleCase(str) {
  return str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
  });
}

var str = "how to convert string to title case with JavaScript";
var result = toTitleCase(str);
console.log(result);
// Output: "How To Convert String To Title Case With JavaScript"

Conclusion

In this tutorial, we discussed two methods to convert strings to title case in JavaScript.

We used the toLowerCase() and toUpperCase() methods to convert a string to title case by converting the entire string to lowercase, and then converting the first letter of each word to uppercase.

We also used the replace() method to convert a string to title case by replacing the first letter of each word with its uppercase equivalent.

Both methods are easy to understand and implement, and the choice of method depends on your personal preference and the requirements of your project.

By the end of this tutorial, you should have a good understanding of how to convert strings to title case in JavaScript.