Back to Snippets
CODE

Convert String to KebabCase

Description

Converts camelCase, snake_case, or space-separated strings to kebab-case

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-world

Usage

Ideal for generating CSS class names, URL slugs, or HTML attribute names from JavaScript identifiers

Tags

String ManipulationFormattingKebabCase