@oxog/string
Version:
Comprehensive string manipulation utilities with zero dependencies
72 lines (71 loc) • 2.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.toCamelCase = toCamelCase;
exports.toPascalCase = toPascalCase;
exports.toSnakeCase = toSnakeCase;
exports.toKebabCase = toKebabCase;
exports.toConstantCase = toConstantCase;
exports.toTitleCase = toTitleCase;
exports.toSentenceCase = toSentenceCase;
function toCamelCase(str) {
if (!str || typeof str !== 'string')
return '';
return str
.replace(/[^a-zA-Z0-9]+(.)/g, (_, char) => char.toUpperCase())
.replace(/^[A-Z]/, char => char.toLowerCase());
}
function toPascalCase(str) {
return str
.replace(/[^a-zA-Z0-9]+(.)/g, (_, char) => char.toUpperCase())
.replace(/^[a-z]/, char => char.toUpperCase());
}
function toSnakeCase(str) {
return str
.replace(/([a-z])([A-Z])/g, '$1_$2')
.replace(/[^a-zA-Z0-9]/g, '_')
.replace(/_+/g, '_')
.replace(/^_|_$/g, '')
.toLowerCase();
}
function toKebabCase(str) {
return str
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[^a-zA-Z0-9]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.toLowerCase();
}
function toConstantCase(str) {
return toSnakeCase(str).toUpperCase();
}
function toTitleCase(str, locale) {
const words = str.toLowerCase().split(/\s+/);
const minorWords = new Set([
'a', 'an', 'and', 'as', 'at', 'but', 'by', 'for', 'if', 'in', 'nor', 'of',
'on', 'or', 'so', 'the', 'to', 'up', 'yet'
]);
return words.map((word, index) => {
if (index === 0 || index === words.length - 1 || !minorWords.has(word)) {
return capitalizeWord(word, locale);
}
return word;
}).join(' ');
}
function toSentenceCase(str) {
if (!str)
return str;
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
function capitalizeWord(word, locale) {
if (!word)
return word;
if (locale && typeof Intl !== 'undefined') {
try {
return word.charAt(0).toLocaleUpperCase(locale) + word.slice(1);
}
catch (_a) {
// Fall back to default if locale is invalid
}
}
return word.charAt(0).toUpperCase() + word.slice(1);
}