Created
January 30, 2021 16:31
-
-
Save pbatey/eb054ffcf2edfd22f267425fba6751dc to your computer and use it in GitHub Desktop.
Convert camelCase and snake_case to Word Case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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