Created
April 22, 2024 14:28
-
-
Save moitorrijos/f2663c5da5a173aaf83db73e9680ef90 to your computer and use it in GitHub Desktop.
A function to convert any string to title case including non capitalizing words in english and spanish
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(str: string | undefined | null) { | |
if (!str) return ""; | |
const nonCapitalizedWords = ["a", "an", "the", "and", "but", "or", "nor", "for", "yet", "so", "as", "at", "by", "for", "in", "of", "on", "per", "to", "with"]; | |
const nonCapitalizedWordsSpanish = ["un", "una", "unos", "unas", "el", "la", "los", "las", "y", "pero", "o", "ni", "por", "aún", "así", "como", "en", "por", "para", "de", "del", "al", "con"]; | |
return str.replace(/\w\S*/g, (txt: string) => { | |
if ([ | |
...nonCapitalizedWords, | |
...nonCapitalizedWordsSpanish | |
].includes(txt.toLowerCase())) { | |
return txt.toLowerCase(); | |
} else { | |
return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase(); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment