brandonscript brandonscript - 5 months ago 174
Javascript Question

Lodash title case (uppercase first letter of every word)

I'm looking through the lodash docs and other Stack Overflow questions - while there are several native JavaScript ways of accomplishing this task, is there a way I can convert a string to title case using purely lodash functions (or at least existing prototypal functions) so that I don't have to use a regular expression or define a new function?

e.g.

This string ShouLD be ALL in title CASe


should become

This String Should Be All In Title Case

Answer

This can be done with a small modification of startCase:

_.startCase(_.toLower(str));

var str = "This string ShouLD be ALL in title CASe";
str = _.startCase(_.toLower(str));
console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>