utilcn logoutilcn
String Utilities

toKebabCase

Converts a string to kebab-case with proper acronym handling

Usage

import { toKebabCase } from '@/lib/to-kebab-case';

const result = toKebabCase("Hello World Again");
console.log(result); // "hello-world-again"

Installation

pnpm dlx shadcn@latest add https://utilcn.dev/r/to-kebab-case.json
bunx --bun shadcn@latest add https://utilcn.dev/r/to-kebab-case.json
npx shadcn@latest add https://utilcn.dev/r/to-kebab-case.json
yarn shadcn@latest add https://utilcn.dev/r/to-kebab-case.json

Parameters

ParameterTypeDescription
strstringThe input string

Returns

string - The kebab-cased string.

Examples

toKebabCase("Hello World Again"); // "hello-world-again"
toKebabCase("XMLHttpRequest"); // "xml-http-request"
toKebabCase("user_name"); // "user-name"
toKebabCase("APIResponse"); // "api-response"
toKebabCase("HTML Parser"); // "html-parser"

Implementation

export function toKebabCase(str: string): string {
  return (
    str
      // Split acronym groups (e.g. "XMLHttp" -> "XML-Http")
      .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
      // Split between a lowercase/digit and an uppercase (e.g. "testHTTP" -> "test-HTTP")
      .replace(/([a-z\d])([A-Z])/g, '$1-$2')
      // Replace spaces and underscores with hyphens
      .replace(/[\s_]+/g, '-')
      .toLowerCase()
      // Remove leading and trailing hyphens
      .replace(/^-+|-+$/g, '')
  );
}