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.
Code
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 earlythrowwhen 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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Case ConverterConvert text between lowercase, uppercase, title, sentence, camelCase, snake_case, and kebab-case while preserving Unicode letters and numbers.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.