Lodash title case (uppercase first letter of every word)

Solution 1:

This can be done with a small modification of startCase:

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

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

Solution 2:

_.startCase(_.camelCase(str))

For non-user-generated text, this handles more cases than the accepted answer

> startCase(camelCase('myString'))
'My String'
> startCase(camelCase('my_string'))
'My String'
> startCase(camelCase('MY_STRING'))
'My String'
> startCase(camelCase('my string'))
'My String'
> startCase(camelCase('My string'))
'My String'

Solution 3:

with lodash version 4.

_.upperFirst(_.toLower(str))

Solution 4:

'This string ShouLD be ALL in title CASe'
  .split(' ')
  .map(_.capitalize)
  .join(' ');

Solution 5:

There are mixed answers to this question. Some are recommending using _.upperFirst while some recommending _.startCase.

Know the difference between them.

i) _.upperFirst will transform the first letter of your string, then string might be of a single word or multiple words but the only first letter of your string is transformed to uppercase.

_.upperFirst('jon doe')

output:

Jon doe

check the documentation https://lodash.com/docs/4.17.10#upperFirst

ii) _.startCase will transform the first letter of every word inside your string.

_.startCase('jon doe')

output:

Jon Doe

https://lodash.com/docs/4.17.10#startCase