Regex to Convert snake_case to camelCase
Regex pattern to convert snake_case identifiers to camelCase or PascalCase. Handles leading underscores, double underscores, and digit-adjacent transitions.
Detailed Explanation
snake_case to camelCase
Going the other direction, this conversion transforms identifiers like get_user_name into getUserName.
Basic Conversion (snake_case to camelCase)
str.replace(/_([a-z])/g, (_, ch) => ch.toUpperCase())
Each _x becomes X.
snake_case to PascalCase
str.replace(/(?:^|_)([a-z])/g, (_, ch) => ch.toUpperCase())
Same logic, but capitalizes the first letter too.
Tested Examples
| Input | camelCase | PascalCase |
|---|---|---|
foo_bar |
fooBar |
FooBar |
get_user_name |
getUserName |
GetUserName |
api_v2_endpoint |
apiV2Endpoint |
ApiV2Endpoint |
_private_field |
PrivateField |
PrivateField |
http_request |
httpRequest |
HttpRequest |
already_lower |
alreadyLower |
AlreadyLower |
Handle Leading Underscores Carefully
_privateField is conventional in JavaScript for private fields. To preserve a single leading underscore:
str.replace(/(_)?([a-z]+)(?:_([a-z]+))*?/, ...)
A safer approach: split on _, treat the first segment as-is or empty, and capitalize the rest.
function snakeToCamel(s) {
if (s.startsWith("_")) {
return "_" + snakeToCamel(s.slice(1));
}
return s.replace(/_([a-z0-9])/g, (_, ch) => ch.toUpperCase());
}
Double Underscores
a__b becomes a_B with the basic regex (the second underscore is preserved). To collapse:
str.replace(/_+([a-z])/g, (_, ch) => ch.toUpperCase())
From kebab-case Too
Same logic, swap the underscore for a hyphen:
str.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase())
Practical Note
When mapping between API styles, enforce the convention with TypeScript types and an automatic transformation layer (e.g. humps library) rather than scattering regexes throughout the codebase.
Use Case
Mapping a Python REST API’s snake_case JSON keys to JavaScript camelCase consumer code, or normalizing a database schema during a TypeScript ORM migration.