ArticleZip > Convert String To Title Case With Javascript

Convert String To Title Case With Javascript

When working with strings in JavaScript, there might be instances where you need to convert a string to title case. Title case means that the first letter of each word is capitalized while the rest of the letters are in lowercase. This can be particularly useful when you want to make your text look more polished and professional. In this article, we will walk you through a simple and effective way to convert a string to title case using JavaScript.

To start off, let's create a function that will handle the conversion process. You can name this function whatever you like, but for demonstration purposes, we will call it `convertToTitleCase`. Here is the basic structure of the function:

Javascript

function convertToTitleCase(str) {
  // Code to convert string to title case will go here
}

Now, inside the function, we need to split the input string into an array of words so that we can capitalize the first letter of each word. We can achieve this using the `split` method in JavaScript, which allows us to split a string into an array based on a separator. In this case, we will split the string based on whitespace to separate the words. Here's how you can do it:

Javascript

function convertToTitleCase(str) {
  let words = str.split(" ");
}

Next, we will iterate over each word in the array and capitalize the first letter while keeping the rest of the letters in lowercase. To do this, we will use the `map` method along with a combination of string methods such as `toUpperCase` and `slice`. Here's the code to accomplish this:

Javascript

function convertToTitleCase(str) {
  let words = str.split(" ");

  let titleCaseWords = words.map(word => {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });

  return titleCaseWords.join(" ");
}

With the code above, we split the input string into an array of words, capitalized the first letter of each word, converted the rest of the word to lowercase, and finally joined the words back together to form the title case string. Now, you can simply call the `convertToTitleCase` function with a string input to see the magic happen!

Javascript

let inputString = "example string to convert";
let titleCaseString = convertToTitleCase(inputString);

console.log(titleCaseString); // Output: "Example String To Convert"

By following these simple steps, you can easily convert any string to title case using JavaScript. Whether you are working on a personal project or a professional website, this handy function can add a touch of refinement to your text. So go ahead, give it a try, and elevate the presentation of your strings with title case formatting!