- Instant help with your JavaScript coding problems

Convert string to title case in JavaScript

Question:
How to convert string to title case in JavaScript?
Answer:
function toTitleCase(str){
    return (' '+str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => ' ' + chr.toUpperCase()).trim();
}

console.log(toTitleCase('the name field id     is name-field_id')); // The Name Field Id Is Name Field Id
Description:

Title case or headline case is a style of capitalization used for rendering the titles of published works or works of art in English. When using the title case, all words are capitalized except for minor words. The solution here doesn't properly achieve this definition as it doesn't care about minor words.

Share "How to convert string to title case in JavaScript?"