A Simple Capitalize Function For JavaScript
In Lodash, there is no way to capitalize every word in a sentence which is useful for formatting strings for titles and other user displayed UI elements. Firstly, there is a capitalize function, but it is only meant for one word:
console.log(_.capitalize('test')); // Test console.log(_.capitalize('This string, ShouLD be ALL in title CASe')); // This string, should be all in title case
There are a bunch of other tactics using different Lodash functions, but they all miss significant edge cases. Which is why I chose such a complex example from above. Instead, the most correct strategy is to simply loop through each word and capitalize them all:
const sentence = 'This string, ShouLD be ALL in title CASe'; const result = sentence.split(' ') .map((word) => _.capitalize(word)) .join(' '); console.log(result); // This String, Should Be All In Title Case
Note that (_.words)[https://lodash.com/docs/4.17.11#words] removes some punctiation which is why I used a split instead.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/capitalizeSentence.js















