text-title-case
Version:
Convert a text into title case following English rules
53 lines (52 loc) • 1.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.titleCase = titleCase;
const text_no_case_1 = require("text-no-case");
const text_upper_case_first_1 = require("text-upper-case-first");
// Small words that should not be capitalized unless they are at the beginning or end
const SMALL_WORDS = new Set([
"a",
"an",
"and",
"at",
"but",
"by",
"en",
"for",
"if",
"in",
"nor",
"of",
"on",
"or",
"per",
"so",
"the",
"to",
"up",
"via",
"yet",
]);
function titleCaseTransform(input, index, parts) {
const word = input.toLowerCase();
// Always capitalize first and last words
if (index === 0 || index === parts.length - 1) {
return (0, text_upper_case_first_1.upperCaseFirst)(word);
}
// Don't capitalize small words in the middle
if (SMALL_WORDS.has(word)) {
return word;
}
// Capitalize all other words
return (0, text_upper_case_first_1.upperCaseFirst)(word);
}
function titleCase(input, options = {}) {
// Handle null/undefined inputs gracefully
if (!input)
return "";
return (0, text_no_case_1.noCase)(input, {
delimiter: " ",
transform: titleCaseTransform,
...options,
});
}