Skip to content

camelCase function ​

Converts a string to camelCase; acronyms are words (XMLHttpRequest → xmlHttpRequest).

ts
import { camelCase } from 'utils';

Signature ​

ts
export function camelCase(input: string): string

Parameters ​

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

Returns ​

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

Example ​

ts
camelCase('user-id'); // 'userId'
camelCase('XML HTTP request'); // 'xmlHttpRequest'

Tests ​

Line coverage: 100 %.

  • ✅ converts "user-id" to "userId"
  • ✅ converts "user_id" to "userId"
  • ✅ converts "User Id" to "userId"
  • ✅ converts "USER_ID" to "userId"
  • ✅ converts "userId" to "userId"
  • ✅ converts "XMLHttpRequest" to "xmlHttpRequest"
  • ✅ converts "speed 2 knots" to "speed2Knots"
  • ✅ converts "" to ""

Source ​

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

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

/**
 * Converts a string to camelCase; acronyms are words (`XMLHttpRequest` → `xmlHttpRequest`).
 *
 * @param input - The identifier or sentence to convert, in any case style.
 * @returns The camelCase string; `''` when the input has no word.
 * @example
 * camelCase('user-id'); // 'userId'
 * camelCase('XML HTTP request'); // 'xmlHttpRequest'
 */
export function camelCase(input: string): string {
  return splitWords(input)
    .map((word, index) => (index === 0 ? word.toLowerCase() : capitalize(word.toLowerCase())))
    .join('');
}
Test file
ts
import { camelCase } from './camel-case';

describe(camelCase, () => {
  it.for([
    ['user-id', 'userId'],
    ['user_id', 'userId'],
    ['User Id', 'userId'],
    ['USER_ID', 'userId'],
    ['userId', 'userId'],
    ['XMLHttpRequest', 'xmlHttpRequest'],
    ['speed 2 knots', 'speed2Knots'],
    ['', ''],
  ] as const)('converts %j to %j', ([input, expected]) => {
    expect(camelCase(input)).toBe(expected);
  });
});

Keywords: camel, case, strings, function

Generated from the JSDoc of the sources.