Hi Friends đź‘‹,

Welcome to Infinitbility ❤️!

Today, we are going to learn how to convert string in any case like camel case, paskal case to title case in typescript, here we will create toTitleCase() custom method to convert string any case to title case.

Well, let’s create a function which return the provided string with the first letter of each word capitalized and Make sure the rest of the word is in lower case.

let’s dive in code…

/**
 * Convert string to title case
 * 
 * @param str 
 * @returns title case string
 */
const toTitleCase = (str: string) => {
  return str.toLowerCase().split(' ').map(function(word) {
    return word.replace(word[0], word[0].toUpperCase());
  }).join(' ');
}

toTitleCase(`I'm a infinitbility`);
toTitleCase(`WELCOME TO INFINITBILITY`);

Well, when you run above code, you can able to see above string converted in the title case.

For now, let’s check output.

Output

TypeScript, convert string to title case example
TypeScript, convert string to title case example

All the best đź‘Ť.