JavaScript: Convert String to Title Case

How can I convert a string to a Title Case using JavaScript? For example, I want to transform “john smith” into “John Smith.” I’m looking for a simple solution, ideally a one- or two-liner, rather than something complicated like John Resig’s solution.

Specifically, I want to know how to achieve this with a JavaScript title case.

You can use the split() method to break the string into words and then capitalize the first letter of each word using map() combined with charAt() and toUpperCase(). Finally, join the words back together. Here’s a concise implementation:


const titleCase = str => str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');

console.log(titleCase("john smith")); // John Smith

This is a simple and effective way to achieve JavaScript title case.

Another quick and clean way is using a regular expression to target the first letter of each word and convert it to uppercase. You can handle it like this:


const titleCase = str => str.replace(/\b\w/g, char => char.toUpperCase());

console.log(titleCase("john smith")); // John Smith

This regex-based approach efficiently addresses the problem of achieving JavaScript title case.

You could also use the reduce() method to build a title-cased string iteratively. Here’s how it works:


const titleCase = str => str.split(' ').reduce((acc, word) => acc + ' ' + word.charAt(0).toUpperCase() + word.slice(1), '').trim();

console.log(titleCase("john smith")); // John Smith

This method demonstrates yet another effective technique for JavaScript title case conversion, especially if you like using functional array methods.