Skip to content

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

ParameterTypeDescription
strstringA string in camelCase or PascalCase form.

Returns

string

The SCREAMING_SNAKE_CASE equivalent.

Remarks

Applies two regex passes before uppercasing:

  1. Splits ACRONYM boundaries where an uppercase run transitions to a lowercase word (e.g., URL + ValueURL_Value).
  2. Splits camelCase boundaries where a lowercase/digit is followed by an uppercase letter (e.g., port + Numberport_Number).

This means acronyms at the end of a word (parseJSONPARSE_JSON) and digits adjacent to word boundaries (version2IdVERSION2_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 .env documentation 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 getHTTPSUrlGET_HTTPS_URLgetHttpsUrl, losing the original casing of consecutive uppercase letters.
  • NEVER feed already-snake-cased input — BECAUSE PORT_NUMBERPORT__NUMBER (double underscore) due to the camelCase split regex firing on the _N boundary.

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

Released under the MIT License.