Skip to content
VersionSize

camelCase

The camelCase utility transforms a string into camelCase format (lower case first letter, with subsequent words capitalized and no separators). It is ideal for normalizing user input or converting string keys into standard JavaScript property names.

Implementation

View Source Code
ts
import { normalizeCase } from './_caseUtils';

/**
 * Converts a string to camel case.
 *
 * @example
 * ```ts
 * const text = 'hello world';
 * camelCase(text); // 'helloWorld'
 * ```
 *
 * @param str - The string to convert.
 * @returns The converted string.
 */
export function camelCase(str: string): string {
  return normalizeCase(str, ' ')
    .replace(/[^a-zA-Z0-9]+(.)/g, (_, char) => char.toUpperCase()) // Basic split by non-alphanumeric
    .replace(/^./, (char) => char.toLowerCase());
}

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Versatile Parsing: Handles spaces, dashes, underscores, and dots as word separators.
  • Smart Capitalization: Properly handles mixed-case strings and acronyms.

API

ts
function camelCase(input: string): string;

Parameters

  • input: The string to transform.

Returns

  • The transformed string in camelCase.

Examples

Basic Conversion

ts
import { camelCase } from '@vielzeug/toolkit';

camelCase('hello world'); // 'helloWorld'
camelCase('foo-bar'); // 'fooBar'
camelCase('USER_PROFILE'); // 'userProfile'
camelCase('data.meta.id'); // 'dataMetaId'

Handling Complex Strings

ts
import { camelCase } from '@vielzeug/toolkit';

camelCase('  multiple   spaces  '); // 'multipleSpaces'
camelCase('--kebab--case--'); // 'kebabCase'
camelCase('mixed_Case-string'); // 'mixedCaseString'

Implementation Notes

  • Trims leading and trailing whitespace before processing.
  • All non-alphanumeric characters are treated as potential word separators.
  • Throws TypeError if the input is not a string.

See Also