This should cover most basic use cases.
const capitalize = (str) => {
if (typeof str !== 'string') {
throw Error('Feed me string')
} else if (!str) {
return ''
} else {
return str
.split(' ')
.map(s => {
if (s.length == 1 ) {
return s.toUpperCase()
} else {
const firstLetter = s.split('')[0].toUpperCase()
const restOfStr = s.substr(1, s.length).toLowerCase()
return firstLetter + restOfStr
}
})
.join(' ')
}
}
capitalize('THIS IS A BOOK') // => This Is A Book
capitalize('this is a book') // => This Is A Book
capitalize('a 2nd 5 hour boOk thIs weEk') // => A 2nd 5 Hour Book This Week
Edit: Improved readability of mapping.