String Case Conversion: camelCase, snake_case, kebab-case

Convert identifiers between camelCase, snake_case and kebab-case with word-boundary splitting, input validation and predictable output.

JavascriptData Integrity

Code

javascriptsnippet
24 lines
function splitWords(input) {
  if (typeof input !== "string") throw new TypeError("input must be a string");
  return input
    .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
    .replace(/[_-]+/g, " ")
    .trim()
    .split(/\s+/)
    .filter(Boolean)
    .map((word) => word.toLowerCase());
}

export function toCamelCase(input) {
  return splitWords(input)
    .map((word, index) => (index === 0 ? word : word[0].toUpperCase() + word.slice(1)))
    .join("");
}

export function toSnakeCase(input) {
  return splitWords(input).join("_");
}

export function toKebabCase(input) {
  return splitWords(input).join("-");
}

What the code does

String Case Conversion: camelCase, snake_case, kebab-case keeps everything in the functions splitWords, toCamelCase, toSnakeCase and toKebabCase.

Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

What to watch for

  • The guard typeof input !== "string" short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is export function toCamelCase(input)

toCamelCase is the public entry point; everything else in the file exists to support it.

Key statements

if (typeof input !== "string") throw new TypeError("input must be a string");
.map((word) => word.toLowerCase());
return splitWords(input).join("_");

Interactive Tools for This Topic

FAQ

Does the code validate its input?
It throws `TypeError` before any real work runs, via the guard `typeof input !== "string"` — handle it at the call site or let it propagate deliberately.
Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `splitWords`, `toCamelCase`, `toSnakeCase` at load time.