If you have been a Javascript developer for any length of time, you know that the built-in functions like toLowerCase()
and toUpperCase()
suffice for converting a string to all lower case or all upper case characters, respectively.
But what if you want to capitalize only the first letter in a string, and make all the remaining characters lowercase? And you want to do this on every word in a string, in a string of arbitrary length?
Basically, there is no native Javascript function for doing so and you have to roll your own code.
Fortunately, this is fairly trivial. Using string.replace we match any word in the string, including words with quotes, with the regex /\b[\w']+\b/g
, and in our replacer function take the 0th character in the string, call toUpperCase()
on it and return the result of this and calling toLowerCase()
on the rest of the string.
Code:
const titleCase = (str) => {
return str.replace(/\b[\w']+\b/g, (txt) => {
return `${txt.charAt(0).toUpperCase()}${txt.slice(1).toLowerCase()}`;
});
};
Usage:
titleCase('We should play with legos at camp.')
=> We Should Play With Legos At Camp.
titleCase('NOTHING SEEMED OUT OF PLACE EXCEPT THE WASHING MACHINE IN THE BAR.')
=> Nothing Seemed Out Of Place Except The Washing Machine In The Bar.