Skip to content

trainCase function ​

Converts a string to Train-Case: capitalized words joined with -, as in HTTP header names.

ts
import { trainCase } from 'utils';

Signature ​

ts
export function trainCase(input: string): string

Parameters ​

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

Returns ​

The Train-Case string; '' when there is no word.

Example ​

ts
trainCase('contentType'); // 'Content-Type'
trainCase('x_request_id'); // 'X-Request-Id'

Tests ​

Line coverage: 100 %.

  • ✅ converts "contentType" to "Content-Type"
  • ✅ converts "x_request_id" to "X-Request-Id"
  • ✅ converts "" to ""

Source ​

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

Uses ​

  • capitalize: Upper-cases the first character of a string, even outside the basic Unicode plane.
  • splitWords: Splits a string into words, whatever its case style (camelCase, kebab-case, snake_case, spaces…), in one pass.

Files it needs ​

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

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

/**
 * Converts a string to Train-Case: capitalized words joined with `-`, as in HTTP header names.
 *
 * @param input - The identifier or sentence to convert, in any case style.
 * @returns The Train-Case string; `''` when there is no word.
 * @example
 * trainCase('contentType'); // 'Content-Type'
 * trainCase('x_request_id'); // 'X-Request-Id'
 */
export function trainCase(input: string): string {
  return splitWords(input)
    .map((word) => capitalize(word.toLowerCase()))
    .join('-');
}
Test file
ts
import { trainCase } from './train-case';

describe(trainCase, () => {
  it.for([
    ['contentType', 'Content-Type'],
    ['x_request_id', 'X-Request-Id'],
    ['', ''],
  ] as const)('converts %j to %j', ([input, expected]) => {
    expect(trainCase(input)).toBe(expected);
  });
});

Keywords: train, case, strings, function

Generated from the JSDoc of the sources.