|
| 1 | +/** |
| 2 | + * Capitalizes the first letter of a string |
| 3 | + * @param {string} str - The string to capitalize |
| 4 | + * @returns {string} The capitalized string |
| 5 | + */ |
| 6 | +export function capitalize(str) { |
| 7 | + if (!str || typeof str !== 'string') { |
| 8 | + return str; |
| 9 | + } |
| 10 | + return str.charAt(0).toUpperCase() + str.slice(1); |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Converts a string to kebab-case (dasherized) |
| 15 | + * @param {string} str - The string to dasherize |
| 16 | + * @returns {string} The dasherized string |
| 17 | + */ |
| 18 | +export function dasherize(str) { |
| 19 | + if (!str || typeof str !== 'string') { |
| 20 | + return str; |
| 21 | + } |
| 22 | + return str |
| 23 | + .replace(/([a-z\d])([A-Z])/g, '$1-$2') // Add dash between camelCase |
| 24 | + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1-$2') // Handle consecutive capitals |
| 25 | + .replace(/[ _]/g, '-') // Replace spaces and underscores with dashes |
| 26 | + .toLowerCase(); |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * Converts a string to PascalCase (classified) |
| 31 | + * @param {string} str - The string to classify |
| 32 | + * @returns {string} The classified string |
| 33 | + */ |
| 34 | +export function classify(str) { |
| 35 | + if (!str || typeof str !== 'string') { |
| 36 | + return str; |
| 37 | + } |
| 38 | + |
| 39 | + // If the string contains separators (spaces, dashes, underscores), split and classify |
| 40 | + if (/[\s_-]/.test(str)) { |
| 41 | + return str |
| 42 | + .split(/[\s_-]+/) |
| 43 | + .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) |
| 44 | + .join(''); |
| 45 | + } |
| 46 | + |
| 47 | + // Otherwise, just capitalize the first letter (preserve camelCase like innerHTML -> InnerHTML) |
| 48 | + return str.charAt(0).toUpperCase() + str.slice(1); |
| 49 | +} |
0 commit comments