How I can convert string to TitalCase in typescript or JavaScript


Sajid Sajid Ansari Asked on Nov 21, 2024
Summary:-

I have a string which can be either LowerCase, UpperCase or TitleCase. I have a requirement to show this string into TitleCase.

For Example If I have a string like heLLo World, Hello World, hello world, HELLO WORLD. Then the final result should be Hello World.

I have attemted below options:-

I try ti find the javascript function for this but only able to find toLowerCase() or toUpperCase(), I didn't find any function to convert string into TitleCase

I have tried below troubleshooting methods:-

Try to search on google but didn't found any solution

I have facing below issue:-

Need this solution ASAP

Urgency of Question:-

Need Soon

Skill Level:-

Beginner

Admin Admin STG Commented on Nov 21, 2024

In TypeScript, you can convert a string to title case by following these steps:

1. Create a function that accepts a string parameter:

function toTitleCase(input: string): string {
  // logic goes here
  // Convert the input string to lowercase using the toLowerCase() method
  const lowercaseInput = input.toLowerCase();
  // Split the lowercase string into an array of words using the split() method and a space (” “) as the separator
  const words = lowercaseInput.split(" ");
  // Iterate over each word in the array and capitalize the first letter of each word using the charAt() and toUpperCase() methods
  for (let i = 0; i < words.length; i++) {
    words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
  }
  // Join the capitalized words back into a single string using the join() method with a space (” “) as the separator
  const titleCase = words.join(" ");
  return titleCase;
}

. Now, you can use the toTitleCase function to convert a string to title case:

const inputString = "hello world";
const titleCaseString = toTitleCase(inputString);
console.log(titleCaseString); // Output: "Hello World"

This logic converts each word in the string to lowercase and then capitalizes the first letter of each word, resulting in title case format.

Do you know the Answer?

Got a question? Ask our extensive community for help. Submit Your Question

Recent Posts