How to Convert Strings to Title Case in TypeScript
Q: Create a TypeScript function that converts a string to title case (capitalizing the first letter of each word).
- TypeScript
- Senior level question
Explore all the latest TypeScript interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create TypeScript interview for FREE!
Here's an example of a TypeScript function that converts a string to title case:
function toTitleCase(input: string): string { const words = input.toLowerCase().split(' '); const titleCaseWords = words.map((word) => { return word.charAt(0).toUpperCase() + word.slice(1); }); return titleCaseWords.join(' '); } // Usage example const inputString = 'hello world'; const titleCaseString = toTitleCase(inputString); console.log(titleCaseString);
In this example, the toTitleCase function takes a string as input and converts it to title case.
The function first converts the entire string to lowercase using the toLowerCase method and then splits it into an array of individual words using the split method and space (' ') as the separator.
Next, the map method is used to iterate over each word in the array and transform it into title case. For each word, the charAt(0).toUpperCase() method is used to capitalize the first letter, and word.slice(1) is used to retrieve the remaining part of the word.
The transformed words are then joined back together using the join method, with a space (' ') as the separator, and the resulting title case string is returned.
In the example usage, the toTitleCase function is called with the input string 'hello world'. The resulting title case string 'Hello World' is then logged to the console.


