Skip to content

constantCase function ​

Converts a string to CONSTANT_CASE: uppercase words joined with _, as in constants and environment variables.

ts
import { constantCase } from 'utils';

Signature ​

ts
export function constantCase(input: string): string

Parameters ​

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

Returns ​

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

Example ​

ts
constantCase('maxChannel'); // 'MAX_CHANNEL'
constantCase('api-base-url'); // 'API_BASE_URL'

Tests ​

Line coverage: 100 %.

  • ✅ converts "maxChannel" to "MAX_CHANNEL"
  • ✅ converts "api-base-url" to "API_BASE_URL"
  • ✅ converts "Half turn" to "HALF_TURN"
  • ✅ converts "MAX_CHANNEL" to "MAX_CHANNEL"
  • ✅ converts "" to ""

Source ​

src/string/constant-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/constant-case.ts imports, directly or not:

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

/**
 * Converts a string to CONSTANT_CASE: uppercase words joined with `_`, as in constants and environment
 * variables.
 *
 * @param input - The identifier or sentence to convert, in any case style.
 * @returns The CONSTANT_CASE string; `''` when the input has no word.
 * @example
 * constantCase('maxChannel'); // 'MAX_CHANNEL'
 * constantCase('api-base-url'); // 'API_BASE_URL'
 */
export function constantCase(input: string): string {
  return splitWords(input)
    .map((word) => word.toUpperCase())
    .join('_');
}
Test file
ts
import { constantCase } from './constant-case';

describe(constantCase, () => {
  it.for([
    ['maxChannel', 'MAX_CHANNEL'],
    ['api-base-url', 'API_BASE_URL'],
    ['Half turn', 'HALF_TURN'],
    ['MAX_CHANNEL', 'MAX_CHANNEL'],
    ['', ''],
  ] as const)('converts %j to %j', ([input, expected]) => {
    expect(constantCase(input)).toBe(expected);
  });
});

Keywords: constant, case, strings, function

Generated from the JSDoc of the sources.