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
'This string ShouLD be ALL in title CASe'
.split(' ')
.map(_.capitalize)
.join(' ');
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>
Not as concise as @4castle's answer, but descriptive and lodash-full, nonetheless...
var basicTitleCase = _
.chain('This string ShouLD be ALL in title CASe')
.toLower()
.words()
.map(_.capitalize)
.join(' ')
.value()
console.log('Result:', basicTitleCase)
console.log('Exact Match:' , basicTitleCase === '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>
const titleCase = str =>
str
.split(' ')
.map(str => {
const word = str.toLowerCase()
return word.charAt(0).toUpperCase() + word.slice(1)
})
.join(' ')
You can also split out the map function to do separate words
var s = 'This string ShouLD be ALL in title CASe';
_.map(s.split(' '), (w) => _.capitalize(w.toLowerCase())).join(' ')
Unless i missed it, lodash doesnt have its own lower/upper case methods.
_.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'