Convert String to KebabCase
Converts camelCase, snake_case, or space-separated strings to kebab-case
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 kebab-case
* @param str String to convert
* @returns kebab-case string
*/
function toKebabCase(str: string): string {
return str
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
.replace(/[-_s]+/g, '-')
.toLowerCase();
}
// Usage Example
console.log(toKebabCase('helloWorld')); // hello-world
console.log(toKebabCase('hello_world')); // hello-world
console.log(toKebabCase('Hello World')); // hello-worldWhen to use it
Ideal for generating CSS class names, URL slugs, or HTML attribute names from JavaScript identifiers
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 expression finds lowercase-to-uppercase boundaries and separator runs, inserts dashes, then normalizes the result to lowercase. This creates familiar kebab-case values for CSS classes, slugs, and data attributes.
What to watch for
Naive case splitting can turn consecutive capitals into unexpected words and can collapse distinct Unicode input into the same output. A URL slug additionally needs transliteration, reserved-word policy, length limits, and collision handling.
Production use
Use this function for internal identifiers generated from controlled English labels. For permanent public URLs, store the chosen slug, validate uniqueness, and avoid recomputing it whenever a display title changes.
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.