Skip to content

sentenceCase function ​

Converts an identifier to a sentence, to turn a key into a label: the first word capitalized, the others in lower case, acronyms kept.

ts
import { sentenceCase } from 'utils';

Signature ​

ts
export function sentenceCase(input: string): string

Parameters ​

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

Returns ​

The sentence; '' when the input has no word.

Example ​

ts
sentenceCase('engineRoomTemperature'); // 'Engine room temperature'
sentenceCase('max_speed_GPS'); // 'Max speed GPS'

Tests ​

Line coverage: 100 %.

  • ✅ converts "engineRoomTemperature" to "Engine room temperature"
  • ✅ converts "max_speed_GPS" to "Max speed GPS"
  • ✅ converts "user-id" to "User id"
  • ✅ converts "SPEED" to "SPEED"
  • ✅ converts "depth2Meters" to "Depth 2 meters"
  • ✅ converts "" to ""

Source ​

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

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

/**
 * Converts an identifier to a sentence, to turn a key into a label: the first word capitalized, the others in
 * lower case, acronyms kept.
 *
 * @param input - The identifier or sentence to convert, in any case style.
 * @returns The sentence; `''` when the input has no word.
 * @example
 * sentenceCase('engineRoomTemperature'); // 'Engine room temperature'
 * sentenceCase('max_speed_GPS'); // 'Max speed GPS'
 */
export function sentenceCase(input: string): string {
  const sentence = splitWords(input)
    .map((word) => (word === word.toUpperCase() ? word : word.toLowerCase()))
    .join(' ');
  return capitalize(sentence);
}
Test file
ts
import { sentenceCase } from './sentence-case';

describe(sentenceCase, () => {
  it.for([
    ['engineRoomTemperature', 'Engine room temperature'],
    ['max_speed_GPS', 'Max speed GPS'],
    ['user-id', 'User id'],
    ['SPEED', 'SPEED'],
    ['depth2Meters', 'Depth 2 meters'],
    ['', ''],
  ] as const)('converts %j to %j', ([input, expected]) => {
    expect(sentenceCase(input)).toBe(expected);
  });
});

Keywords: sentence, case, strings, function

Generated from the JSDoc of the sources.