objectenvy / toSnakeCase
Function: toSnakeCase()
ts
function toSnakeCase(str): string;Defined in: utils.ts:80
Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE.
Parameters
| Parameter | Type | Description |
|---|---|---|
str | string | A string in camelCase or PascalCase form. |
Returns
string
The SCREAMING_SNAKE_CASE equivalent.
Remarks
Applies two regex passes before uppercasing:
- Splits
ACRONYMboundaries where an uppercase run transitions to a lowercase word (e.g.,URL+Value→URL_Value). - Splits
camelCaseboundaries where a lowercase/digit is followed by an uppercase letter (e.g.,port+Number→port_Number).
This means acronyms at the end of a word (parseJSON → PARSE_JSON) and digits adjacent to word boundaries (version2Id → VERSION2_ID) are handled correctly. The transformation is non-Unicode-aware.
Use When
- You need to convert a camelCase config key to an env variable name for
envy(). - You're generating
.envdocumentation or scaffolding from TypeScript property names.
Avoid When
- You need a strictly reversible transform —
toCamelCase(toSnakeCase('apiURL'))yields'apiUrl', not'apiURL'.
Pitfalls
- NEVER assume acronym round-trips are lossless — BECAUSE
getHTTPSUrl→GET_HTTPS_URL→getHttpsUrl, losing the original casing of consecutive uppercase letters. - NEVER feed already-snake-cased input — BECAUSE
PORT_NUMBER→PORT__NUMBER(double underscore) due to the camelCase split regex firing on the_Nboundary.
Example
ts
import { toSnakeCase } from 'objectenvy';
toSnakeCase('portNumber'); // 'PORT_NUMBER'
toSnakeCase('logLevel'); // 'LOG_LEVEL'
toSnakeCase('apiURLValue'); // 'API_URL_VALUE'
toSnakeCase('parseJSON'); // 'PARSE_JSON'See
toCamelCase for the inverse operation