Convert string to Title Case with JavaScript using RegEx

18 August, 2014   |   JavaScript

Capitalization is generally used in styling titles and headlines for catching attention to those important parts of the site contents. Title Case is a form of capitalization where first letter of word is written in upper case letter and remaining letters in lower case letters.

JavaScript do not have any native function to convert string into Title Case. Therefore, we will use toUpperCase and toLowerCase functions along with Regular Expression to create a custom function that will convert a given string to Title Case string.

function toTitleCase(str)
    return str.replace(/\w+/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});


You can use this custom Title Case function in converting string values from form fields, titles, headlines, etc.

document.write(toTitleCase('this is a title case string'));
// Output: This Is A Title Case String
form.fieldname.value = toTitleCase(form.fieldname.value);


Leave a Comment