Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

slugToTitle

Converts a slug (kebab-case or snake_case) to a human-readable title.

TypeScript
Copied!
1/**
2 * Converts a slug (kebab-case or snake_case) to a human-readable title.
3 *
4 * @param str - The slug string to convert.
5 * @returns The title-cased string.
6 *
7 * @example
8 * slugToTitle('my-example-slug') => 'My Example Slug'
9 */
10export function slugToTitle(str: string): string {
11  return str
12    .replace(/[-_]+/g, ' ')
13    .replace(/\b\w/g, char => char.toUpperCase());
14}
  • Improves Readability

    Transforms machine-readable slugs (e.g. my-awesome-page) into user-friendly text (My Awesome Page), making it ideal for UI display.

  • Supports Multiple Slug Formats

    Handles both kebab-case and snake_case formats by converting dashes and underscores into spaces.

  • Clean and Concise Implementation

    Utilizes simple regex-based replacements and native string methods for effective and fast transformation.

Tests | Examples

TypeScript
Copied!
1test('slugToTitle - kebab-case', () => {
2  expect(slugToTitle('my-example-slug')).toBe('My Example Slug');
3});
4
5test('slugToTitle - snake_case', () => {
6  expect(slugToTitle('my_example_slug')).toBe('My Example Slug');
7});
8
9test('slugToTitle - mixed separators', () => {
10  expect(slugToTitle('my-slug_example')).toBe('My Slug Example');
11});
12
13test('slugToTitle - single word', () => {
14  expect(slugToTitle('hello')).toBe('Hello');
15});
16
17test('slugToTitle - empty string', () => {
18  expect(slugToTitle('')).toBe('');
19});

Common Use Cases

  • Page Titles in CMS

    Display user-friendly titles derived from route slugs or file names.

  • Breadcrumbs or Navigation Labels

    Convert internal identifiers into readable paths or UI elements.

  • Form Field Labels

    Dynamically create form labels from API field names like user_nameUser Name.

  • Data Transformation Pipelines

    Format column names or keys for export (e.g. CSV headers) in human-readable form.

Codebase: Utilities -> Strings -> slugToTitle | Yevhen Klymentiev