Convert String to CamelCase
Converts kebab-case, snake_case, or space-separated strings to camelCase
Implementation
Copy the complete example or adapt its typed interface to your project. Comments are kept inside the snippet so the intent travels with the code.
/**
* Convert string to camelCase
* @param str String to convert
* @returns camelCase string
*/
function toCamelCase(str: string): string {
return str.replace(/[-_s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
}
// Usage Example
console.log(toCamelCase('hello-world')); // helloWorld
console.log(toCamelCase('hello_world')); // helloWorld
console.log(toCamelCase('hello world')); // helloWorldWhen to use it
Useful for converting API response keys to JavaScript conventions, generating variable names, or processing user input
Review the input assumptions and browser or runtime support before adopting a utility unchanged. Small helpers are easiest to maintain when their contract stays narrow.
Reasoning and trade-offs
How it works
The transformation removes separators and uppercases the following character, producing a compact lower-camel identifier from common spaced, dashed, or underscored text. A leading segment remains lowercase for typical inputs.
What to watch for
A simple expression does not define behavior for acronyms, Unicode case rules, punctuation-only strings, or existing capitals. Different teams also disagree about digits and initialisms such as API or URL.
Production use
Use the helper for controlled labels and configuration keys after documenting the naming policy. For code generation or public identifiers, add fixtures for acronyms, non-English text, repeated separators, and collisions.
Before you ship
- Confirm the input contract with tests that cover empty, invalid, boundary, and representative real-world values before sharing the helper across a codebase.
- Keep the function focused on one responsibility and name any project-specific policy explicitly instead of hiding it inside a generic-looking utility.
- Measure behavior in the browsers or runtime versions your product supports, especially when timing, storage, DOM state, locale, or network access is involved.
- Document the return type, mutation behavior, failure mode, and performance characteristics beside the call site so future maintainers can evaluate changes safely.
- Compare the example with current official platform documentation when it relies on a browser API, language feature, or runtime behavior that may change over time.
- If the helper crosses a trust boundary, validate again on the server and avoid treating browser-side checks, TypeScript annotations, or formatted output as a security guarantee.
- Add a small regression test whenever a real edge case is discovered; concrete examples preserve the reason behind a guard more reliably than a general comment.