CamelCase to snake_case Conversion in JavaScript
Many coding style guides prefer snake_case for variable and function names, enhancing readability and consistency. This challenge asks you to write a JavaScript function that converts strings from camelCase to snake_case. This is a common task in code refactoring and integration projects.
Problem Description
You are tasked with creating a JavaScript function called camelToSnake that takes a string as input and returns a new string with the camelCase format converted to snake_case. The conversion involves inserting an underscore "_" before each uppercase letter (except the first letter of the string) and converting the uppercase letter to lowercase.
Key Requirements:
- The function must handle strings that are already in snake_case or contain no uppercase letters.
- The function should return an empty string if the input is an empty string.
- The function should not modify the original string; it should return a new string.
Expected Behavior:
The function should accurately convert camelCase strings to snake_case, adhering to the rules described above.
Edge Cases to Consider:
- Empty input string.
- String already in snake_case.
- String with consecutive uppercase letters.
- String with numbers or special characters.
- String that is already lowercase.
Examples
Example 1:
Input: "camelCaseString"
Output: "camel_case_string"
Explanation: Underscores are inserted before each uppercase letter and converted to lowercase.
Example 2:
Input: "alreadySnake_case"
Output: "already_snake_case"
Explanation: Existing underscores are preserved, and uppercase letters are converted to lowercase with a preceding underscore.
Example 3:
Input: "HTTPRequest"
Output: "h_t_t_p_request"
Explanation: Consecutive uppercase letters are handled correctly, with an underscore inserted before each.
Example 4:
Input: ""
Output: ""
Explanation: Empty string input returns an empty string.
Example 5:
Input: "lowercaseString"
Output: "lowercase_string"
Explanation: Lowercase strings are converted to snake_case by inserting underscores before any uppercase letters that might appear later.
Constraints
- The input string will only contain alphanumeric characters (a-z, A-Z, 0-9) and underscores (_).
- The input string length can be up to 1000 characters.
- The function should execute in O(n) time complexity, where n is the length of the input string.
Notes
Consider using regular expressions to efficiently identify uppercase letters within the string. Think about how to handle the first letter of the string, as it should not have a preceding underscore. Remember to create a new string rather than modifying the original.