toSlug

toSlug converts text into URL-safe slugs that are consistent and readable.

It lowercases text, removes accents/diacritics, strips unsupported characters, and uses hyphens as the separator.

When to use

  • Creating route segments for blog posts or docs pages.
  • Normalizing category and tag identifiers.
  • Generating stable slugs from user-entered labels.

Behavior notes

  • Empty input returns an empty string.
  • Leading/trailing separators are removed.
  • Repeated spaces, underscores, and hyphens collapse to a single hyphen.
  • Accented latin characters are normalized.

Examples

toSlug('  Building Internal Tooling @ Scale (2026)  ');
// "building-internal-tooling-scale-2026"
toSlug('Crème brûlée: easy recipe');
// "creme-brulee-easy-recipe"

Usage

import { toSlug } from '@branditdev/utils';

const postTitle = '  Building Internal Tooling @ Scale (2026)  ';
const categoryLabel = 'Customer_Success & Support';
const accentedTitle = 'Crème brûlée: easy recipe';

export const toSlugDemo = {
  postSlug: toSlug(postTitle),
  categorySlug: toSlug(categoryLabel),
  accentedSlug: toSlug(accentedTitle),
};

API

toSlug(value): string

Defined in: string/toSlug/toSlug.ts:21

Converts a string into a URL-friendly slug.

The function lowercases text, removes diacritics, normalizes separators, strips unsupported characters, and joins words with hyphens.

Parameters

NameTypeOptionalDefaultDescription
valuestringno-The input text to convert into a slug.

Returns

string

A normalized slug string.

Source

export function toSlug(value: string): string {
  if (value.length === 0) return '';

  const normalized = value
    .toLowerCase()
    .trim()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9\s_-]/g, ' ')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');

  return normalized;
}