UNPKG

case-converters

Version:

A modern TypeScript utility to convert strings and object keys between various case styles like camelCase, snake_case, PascalCase, kebab-case, spongeCase, and more.

92 lines (91 loc) 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Case = void 0; // Exporting the Case class class Case { static camel(str) { return str .toLowerCase() .replace(/([-_\s][a-z])/g, (group) => group.toUpperCase().replace("-", "").replace("_", "").replace(" ", "")); } static capital(str) { const pieces = str.split(" "); for (let i = 0; i < pieces.length; i++) { const j = pieces[i].charAt(0).toUpperCase(); pieces[i] = j + pieces[i].substring(1); } return pieces.join(" "); } static dot(str) { return str .toLowerCase() .replace(/([-_\s][a-z])/g, (group) => group.replace("-", ".").replace("_", ".").replace(" ", ".")); } static pascal(str) { return str .toLowerCase() .replace(/(?:_| |\b)(\w)/g, (_, char) => char.toUpperCase()) // Convert first letter after space/underscore to uppercase .replace(/[_\s]+/g, ""); // Remove underscores and spaces } static train(str) { return str .replace(/\s+/g, "-") .replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match) => match.toUpperCase()); } static kebab(str) { return str.replace(/\s+/g, "-").toLowerCase(); } static sponge(str) { let upper = true; return str .split("") .map((char) => { if (char.match(/[a-zA-Z]/)) { // Only change case for alphabetic characters const result = upper ? char.toUpperCase() : char.toLowerCase(); upper = !upper; // Toggle the case for the next character return result; } return char; // Keep non-alphabetic characters unchanged }) .join(""); } static swap(str) { return str.toUpperCase(); } static title(str) { return str .replace(/\b\w/g, (char) => char.toUpperCase()) .replace(/\s+/g, " "); } static upper(str) { return str.toUpperCase(); } static localeUpper(str, locale) { return str.toLocaleUpperCase(locale); } static lower(str) { return str.toLowerCase(); } static localeLower(str, locale) { return str.toLocaleLowerCase(locale); } static lowerFirst(str) { return str.charAt(0).toLowerCase() + str.slice(1); } static upperFirst(str) { return str.charAt(0).toUpperCase() + str.slice(1); } static isUpper(str) { return str === str.toUpperCase(); } static isLower(str) { return str === str.toLowerCase(); } } exports.Case = Case; Case.constant = (str) => str.toUpperCase().replace(/\s+/g, "_"); Case.no = (str) => str.toLowerCase(); Case.path = (str) => str.toLowerCase().replace(/[_\s]+/g, "/"); Case.sentence = (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); Case.snake = (str) => str.toLowerCase().replace(/\s+/g, "_");