Skip to content

pascalCase function ​

Converts a string to PascalCase: words joined, each capitalized, the rest in lower case.

ts
import { pascalCase } from 'utils';

Signature ​

ts
export function pascalCase(input: string): string

Parameters ​

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

Returns ​

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

Example ​

ts
pascalCase('user-id'); // 'UserId'
pascalCase('ring_buffer'); // 'RingBuffer'

Tests ​

Line coverage: 100 %.

  • ✅ converts "user-id" to "UserId"
  • ✅ converts "ring_buffer" to "RingBuffer"
  • ✅ converts "userId" to "UserId"
  • ✅ converts "HTTP status" to "HttpStatus"
  • ✅ converts "" to ""

Source ​

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

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

/**
 * Converts a string to PascalCase: words joined, each capitalized, the rest in lower case.
 *
 * @param input - The identifier or sentence to convert, in any case style.
 * @returns The PascalCase string; `''` when the input has no word.
 * @example
 * pascalCase('user-id'); // 'UserId'
 * pascalCase('ring_buffer'); // 'RingBuffer'
 */
export function pascalCase(input: string): string {
  return splitWords(input)
    .map((word) => capitalize(word.toLowerCase()))
    .join('');
}
Test file
ts
import { pascalCase } from './pascal-case';

describe(pascalCase, () => {
  it.for([
    ['user-id', 'UserId'],
    ['ring_buffer', 'RingBuffer'],
    ['userId', 'UserId'],
    ['HTTP status', 'HttpStatus'],
    ['', ''],
  ] as const)('converts %j to %j', ([input, expected]) => {
    expect(pascalCase(input)).toBe(expected);
  });
});

Keywords: pascal, case, strings, function

Generated from the JSDoc of the sources.