kebabCase function
Converts a string to kebab-case: lowercase words joined with -, as in file names, CSS classes and URLs.
ts
import { kebabCase } from 'utils';Signature
ts
export function kebabCase(input: string): stringParameters
| Name | Description |
|---|---|
input | The identifier or sentence to convert, in any case style. |
Returns
The kebab-case string; '' when the input has no word.
Example
ts
kebabCase('roundToStep'); // 'round-to-step'
kebabCase('XMLHttpRequest'); // 'xml-http-request'Tests
Line coverage: 100 %.
- ✅ converts "roundToStep" to "round-to-step"
- ✅ converts "RingBuffer" to "ring-buffer"
- ✅ converts "XMLHttpRequest" to "xml-http-request"
- ✅ converts "USER_ID" to "user-id"
- ✅ converts " Hello World " to "hello-world"
- ✅ converts "" to ""
Source
src/string/kebab-case.ts (on GitHub)
Uses
splitWords: Splits a string into words, whatever its case style (camelCase, kebab-case, snake_case, spaces…), in one pass.
Used by
slugify: Turns a text into a URL- and id-friendly slug: accents removed, lower-case words joined with-.
Files it needs
src/string/kebab-case.ts imports, directly or not:
Source code
ts
import { splitWords } from './split-words';
/**
* Converts a string to kebab-case: lowercase words joined with `-`, as in file names, CSS classes and URLs.
*
* @param input - The identifier or sentence to convert, in any case style.
* @returns The kebab-case string; `''` when the input has no word.
* @example
* kebabCase('roundToStep'); // 'round-to-step'
* kebabCase('XMLHttpRequest'); // 'xml-http-request'
*/
export function kebabCase(input: string): string {
return splitWords(input)
.map((word) => word.toLowerCase())
.join('-');
}Test file
ts
import { kebabCase } from './kebab-case';
describe(kebabCase, () => {
it.for([
['roundToStep', 'round-to-step'],
['RingBuffer', 'ring-buffer'],
['XMLHttpRequest', 'xml-http-request'],
['USER_ID', 'user-id'],
[' Hello World ', 'hello-world'],
['', ''],
] as const)('converts %j to %j', ([input, expected]) => {
expect(kebabCase(input)).toBe(expected);
});
});Keywords: kebab, case, strings, function