Created
June 28, 2022 21:38
-
-
Save clhenrick/9f25f75b5c00b64569d579464e99570d to your computer and use it in GitHub Desktop.
JS function to convert strings to title case and ignore certain reserved words such as "a", "an", etc.
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
function toTitleCase(string) { | |
const convertTitleCase = (str) => `${str.charAt(0)}${str.toLowerCase().slice(1)}` | |
const reservedWords = new Set(["a", "an", "at", "in"]); | |
return string | |
.split(" ") | |
.map((s) => { | |
if (reservedWords.has(s)) { | |
return s.toLowerCase(); | |
} | |
return convertTitleCase(s); | |
}).join(" "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment