|
| 1 | +/** |
| 2 | + * Converts a string from snake_case to camelCase. |
| 3 | + * |
| 4 | + * @param {string} str - The input string in snake_case format. |
| 5 | + * @throws {Error} Will throw an error if the input is not a string. |
| 6 | + * @returns {string} The converted string in camelCase format. |
| 7 | + * |
| 8 | + * @example |
| 9 | + * |
| 10 | + * snakeToCamelCase("hello_world"); // Returns "helloWorld" |
| 11 | + * snakeToCamelCase("snake_case_example"); // Returns "snakeCaseExample" |
| 12 | + * snakeToCamelCase("_leading_underscore"); // Returns "leadingUnderscore" |
| 13 | + * snakeToCamelCase("trailing_underscore_"); // Returns "trailingUnderscore" |
| 14 | + * snakeToCamelCase("__multiple__underscores__"); // Returns "multipleUnderscores" |
| 15 | + * snakeToCamelCase("snake_case@example"); // Returns "snakeCaseExample" |
| 16 | + * snakeToCamelCase("_leading_underscore_#"); // Returns "leadingUnderscore" |
| 17 | + * snakeToCamelCase("trailing_underscore_&"); // Returns "trailingUnderscore" |
| 18 | + * snakeToCamelCase(""); // Returns "" |
| 19 | + * |
| 20 | + * @throws {Error} If the input is not a string. |
| 21 | + */ |
| 22 | +function snakeToCamelCase(str) { |
| 23 | + // Will throw an error if the input is not a string. |
| 24 | + if (typeof str !== 'string') { |
| 25 | + throw new Error(`Expected string as input, found ${typeof str}`) |
| 26 | + } |
| 27 | + |
| 28 | + if (str.trim() === '') return '' // Handle empty string |
| 29 | + |
| 30 | + // Remove special characters (excluding underscores) |
| 31 | + const cleanedStr = str.replace(/[^a-zA-Z0-9_]/g, '') |
| 32 | + |
| 33 | + return cleanedStr |
| 34 | + .split('_') |
| 35 | + .filter(Boolean) |
| 36 | + .map((value, index) => { |
| 37 | + return index === 0 |
| 38 | + ? value |
| 39 | + : value.charAt(0).toUpperCase() + value.slice(1) |
| 40 | + }) |
| 41 | + .join('') |
| 42 | +} |
| 43 | + |
| 44 | +export { snakeToCamelCase } |
0 commit comments