utilcn logoutilcn
String Utilities

toCamelCase

Converts a string to camelCase with proper acronym handling

Usage

import { toCamelCase } from '@/lib/to-camel-case';

const result = toCamelCase("hello world-example");
console.log(result); // "helloWorldExample"

Installation

pnpm dlx shadcn@latest add https://utilcn.dev/r/to-camel-case.json
bunx --bun shadcn@latest add https://utilcn.dev/r/to-camel-case.json
npx shadcn@latest add https://utilcn.dev/r/to-camel-case.json
yarn shadcn@latest add https://utilcn.dev/r/to-camel-case.json

Parameters

ParameterTypeDescription
strstringThe input string

Returns

string - The camelCased string.

Examples

toCamelCase("hello world-example"); // "helloWorldExample"
toCamelCase("XMLHttpRequest"); // "xmlHttpRequest"
toCamelCase("user_name"); // "userName"
toCamelCase("API-Response"); // "apiResponse"
toCamelCase("HTML Parser"); // "htmlParser"

Implementation

export function toCamelCase(str: string): string {
  const result = str
    // Split acronym groups into proper boundaries
    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
    // Split between lowercase/digit and uppercase
    .replace(/([a-z\d])([A-Z])/g, '$1 $2')
    // Normalize spaces/underscores/dashes
    .replace(/[-_\s]+/g, ' ')
    // Lowercase everything to start clean
    .toLowerCase()
    // Capitalize first letter of each "word" after the first
    .replace(/\s+(\w)/g, (_, c) => c.toUpperCase())
    // Remove any remaining spaces and trim
    .replace(/\s+/g, '')
    .trim();

  // Ensure first character is lowercase for camelCase
  return result.charAt(0).toLowerCase() + result.slice(1);
}