Skip to content

Instantly share code, notes, and snippets.

@moitorrijos
Created April 22, 2024 14:28
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 moitorrijos/f2663c5da5a173aaf83db73e9680ef90 to your computer and use it in GitHub Desktop.
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
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