Skip to content

Instantly share code, notes, and snippets.

@pbatey
Created January 30, 2021 16:31
Show Gist options
  • Save pbatey/eb054ffcf2edfd22f267425fba6751dc to your computer and use it in GitHub Desktop.
Save pbatey/eb054ffcf2edfd22f267425fba6751dc to your computer and use it in GitHub Desktop.
Convert camelCase and snake_case to Word Case
const noVowelsToUpper = key => key.match(/[aeiouy]/) ? key : key.toUpperCase()
const lowerCaseTwoLetter = w => {
const words = [ 'of', 'to', 'in', 'it', 'is', 'as', 'at', 'by', 'or', 'on', 'if', 'an' ]
if (w.length === 2 && words.indexOf(w.toLowerCase()) >= 0) return w.toLowerCase()
return w
}
const upperCaseTwoLetter = w => {
const words = [ 'CA', 'ID' ]
if (w.length === 2 && words.indexOf(w.toUpperCase()) >= 0) return w.toUpperCase()
return w
}
const upperCaseReplace = w => {
const patterns = [
[/guid$/, ' GUID'],
[/uuid$/, ' UUID'],
[/id$/, ' ID'],
]
patterns.forEach(p => w=w.replace(...p))
return w
}
const lowerCaseReplace = w => {
const patterns = []
patterns.forEach(p => w=w.replace(...p))
return w
}
const camelToSnake = str => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
const initCase = w => w[0].toUpperCase() + w.slice(1)
const toWordCase = w => {
if (!w) return w
return camelToSnake(w).toLowerCase().split(/[ _]/).filter(w=>!!w)
.map(noVowelsToUpper)
.map(upperCaseTwoLetter)
.map(upperCaseReplace)
.map(initCase)
.map(lowerCaseTwoLetter)
.map(lowerCaseReplace)
.join(' ')
}
export default toWordCase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment