Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Created June 28, 2022 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clhenrick/9f25f75b5c00b64569d579464e99570d to your computer and use it in GitHub Desktop.
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.
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