Back to Functions

camelCase

string

Converts string to camel case.

Installation

Import
import { camelCase } from '@tulx/utils';

Source Code

Implementation
/**
 * Converts string to camel case.
 *
 * @param string - The string to convert.
 * @returns Returns the camel cased string.
 *
 * @example
 * ```ts
 * camelCase('Foo Bar'); // 'fooBar'
 * camelCase('--foo-bar--'); // 'fooBar'
 * camelCase('__FOO_BAR__'); // 'fooBar'
 * ```
 */
export function camelCase(string: string): string {
  return string
    .replace(/[\s_-]+/g, ' ')
    .replace(/[A-Z]+/g, (match) => ` ${match.toLowerCase()}`)
    .trim()
    .replace(/\s+(\w)/g, (_, char) => char.toUpperCase())
    .replace(/^[A-Z]/, (char) => char.toLowerCase());
}

Example

import { camelCase } from '@tulx/utils';

camelCase('Foo Bar'); // 'fooBar'
camelCase('--foo-bar--'); // 'fooBar'
camelCase('__FOO_BAR__'); // 'fooBar'

Related Functions