UNPKG

text-case-converter

Version:

[DEPRECATED] A modern TypeScript library to convert strings between various case formats (camelCase, PascalCase, snake_case, etc.).

80 lines (79 loc) 2.62 kB
// src/utils.ts function splitWords(input) { if (typeof input !== "string") throw new TypeError("Input must be a string"); const processed = input.replace(/[_\-\s]+/g, " ").replace(/[^a-zA-Z0-9 ]+/g, " ").trim(); const words = processed.length ? processed.split(/\s+/) : []; const result = []; for (const word of words) { const parts = word.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, "$1 $2").split(" "); for (const part of parts) { if (part.length > 1) { result.push(part.toLowerCase()); } else { result.push(part); } } } const final = []; for (const w of result) { if (/^[a-zA-Z]+[0-9]+$/.test(w) || /^[0-9]+$/.test(w)) { final.push(w); } else if (/^[a-zA-Z]+$/.test(w)) { final.push(w); } else { const match = w.match(/[a-zA-Z]+|[0-9]+/g); if (match) final.push(...match); } } return final; } function capitalize(word) { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); } function lowerFirst(word) { return word.charAt(0).toLowerCase() + word.slice(1); } // src/index.ts function toCamelCase(input) { if (typeof input !== "string") throw new TypeError("Input must be a string"); if (input === "") return ""; const words = splitWords(input); if (words.length === 0) return ""; return [lowerFirst(words[0]), ...words.slice(1).map(capitalize)].join(""); } function toPascalCase(input) { if (typeof input !== "string") throw new TypeError("Input must be a string"); if (input === "") return ""; const words = splitWords(input); if (words.length === 0) return ""; return words.map(capitalize).join(""); } function toSnakeCase(input) { if (typeof input !== "string") throw new TypeError("Input must be a string"); if (input === "") return ""; const words = splitWords(input); if (words.length === 0) return ""; return words.map((w) => w.toLowerCase()).join("_"); } function toKebabCase(input) { if (typeof input !== "string") throw new TypeError("Input must be a string"); if (input === "") return ""; const words = splitWords(input); if (words.length === 0) return ""; return words.map((w) => w.toLowerCase()).join("-"); } function toConstantCase(input) { if (typeof input !== "string") throw new TypeError("Input must be a string"); if (input === "") return ""; const words = splitWords(input); if (words.length === 0) return ""; return words.map((w) => w.toUpperCase()).join("_"); } export { toCamelCase, toConstantCase, toKebabCase, toPascalCase, toSnakeCase }; //# sourceMappingURL=index.js.map