Convert Text to kebab-case
Learn how to convert text to kebab-case (dash-separated lowercase) for CSS class names, URL slugs, and HTML attributes. Understand kebab-case rules and where it is required by convention.
Detailed Explanation
Converting Text to kebab-case
kebab-case (also called dash-case or lisp-case) replaces all spaces and delimiters with hyphens (-) and lowercases every letter. It is called "kebab case" because the words look like pieces of meat on a skewer.
Basic Conversion
Input: User First Name
Output: user-first-name
Input: backgroundColor
Output: background-color
Input: MAX_RETRY_COUNT
Output: max-retry-count
Where kebab-case Is Used
kebab-case is the standard in several important contexts:
CSS Class Names and Properties
/* CSS properties are inherently kebab-case */
.user-profile-card {
background-color: #f0f0f0;
font-size: 16px;
border-radius: 8px;
max-width: 600px;
}
URL Slugs
https://example.com/blog/how-to-learn-javascript
https://example.com/products/wireless-bluetooth-headphones
kebab-case is the recommended format for URL slugs because hyphens are treated as word separators by search engines, improving SEO.
HTML Data Attributes
<div data-user-id="42" data-is-active="true"></div>
CLI Flags and Arguments
npm install --save-dev
docker run --restart=on-failure
git log --oneline --no-merges
File Names (some conventions)
my-component.tsx
user-service.ts
api-utils.js
kebab-case vs. snake_case
Both separate words with a delimiter, but use different characters:
kebab-case: user-first-name
snake_case: user_first_name
The choice depends on the ecosystem: CSS and URLs use kebab-case; Python and databases use snake_case.
Conversion Algorithm
- Insert a hyphen before each uppercase letter that follows a lowercase letter.
- Replace all underscores, dots, and spaces with hyphens.
- Collapse consecutive hyphens into one.
- Lowercase the entire string.
- Trim leading and trailing hyphens.
SEO Implications
Google treats hyphens as word separators but treats underscores as joiners. For example:
"my-blog-post" → Google reads: "my", "blog", "post" (3 separate words)
"my_blog_post" → Google reads: "my_blog_post" (1 combined word)
This is why kebab-case is strongly preferred for URL slugs.
Edge Cases
- Single word:
"hello"→"hello". - Already kebab-case: passes through unchanged.
- Acronyms:
"XMLParser"→"xml-parser". - Numbers:
"step2Next"→"step-2-next"or"step2-next".
Use Case
kebab-case is required for CSS class names, custom CSS properties, URL slugs (for SEO), HTML custom data attributes, CLI flag names, and npm package names. It is also the convention for file naming in Angular projects. Converting to kebab-case is a common step in content management systems that auto-generate URL slugs from titles.