Skip to content

snakeCase function ​

Converts a string to snake_case: lowercase words joined with _, as in database columns and JSON keys.

ts
import { snakeCase } from 'utils';

Signature ​

ts
export function snakeCase(input: string): string

Parameters ​

NameDescription
inputThe identifier or sentence to convert, in any case style.

Returns ​

The snake_case string; '' when the input has no word.

Example ​

ts
snakeCase('userId'); // 'user_id'
snakeCase('Speed in knots'); // 'speed_in_knots'

Tests ​

Line coverage: 100 %.

  • ✅ converts "userId" to "user_id"
  • ✅ converts "Speed in knots" to "speed_in_knots"
  • ✅ converts "ring-buffer" to "ring_buffer"
  • ✅ converts "HTTPStatus" to "http_status"
  • ✅ converts "" to ""

Source ​

src/string/snake-case.ts (on GitHub)

Uses ​

  • splitWords: Splits a string into words, whatever its case style (camelCase, kebab-case, snake_case, spaces…), in one pass.

Files it needs ​

src/string/snake-case.ts imports, directly or not:

Source code
ts
import { splitWords } from './split-words';

/**
 * Converts a string to snake_case: lowercase words joined with `_`, as in database columns and JSON keys.
 *
 * @param input - The identifier or sentence to convert, in any case style.
 * @returns The snake_case string; `''` when the input has no word.
 * @example
 * snakeCase('userId'); // 'user_id'
 * snakeCase('Speed in knots'); // 'speed_in_knots'
 */
export function snakeCase(input: string): string {
  return splitWords(input)
    .map((word) => word.toLowerCase())
    .join('_');
}
Test file
ts
import { snakeCase } from './snake-case';

describe(snakeCase, () => {
  it.for([
    ['userId', 'user_id'],
    ['Speed in knots', 'speed_in_knots'],
    ['ring-buffer', 'ring_buffer'],
    ['HTTPStatus', 'http_status'],
    ['', ''],
  ] as const)('converts %j to %j', ([input, expected]) => {
    expect(snakeCase(input)).toBe(expected);
  });
});

Keywords: snake, case, strings, function

Generated from the JSDoc of the sources.