URL Slug Generation in JavaScript
How to generate URL slugs in JavaScript — with diacritics stripping, Unicode handling, and custom delimiters.
Published:
Tags: URL slug JavaScript, JavaScript slug library, slugify npm package
URL Slug Generation in JavaScript A URL slug is the human-readable path segment that identifies a page — instead of . Generating clean, consistent slugs means handling accented characters, Unicode, special symbols, and edge cases like consecutive hyphens or empty results. --- What Makes a Good Slug A well-formed slug is: Lowercase — not Hyphen-delimited — spaces become , not or ASCII-safe — diacritics stripped or transliterated Concise — stop words ("a", "the", "and") removed for long titles Idempotent — slugifying a slug produces the same slug Search engines prefer hyphens as word separators. Google's John Mueller has confirmed that hyphens are treated as word separators while underscores are not, affecting how individual keywords are recognized in the path. A Minimal Hand-Written Slug…
Frequently Asked Questions
How do I generate a slug in JavaScript?
A minimal slug function lowercases the string, normalizes Unicode to NFD, strips diacritics, replaces non-alphanumeric characters with hyphens, and collapses consecutive hyphens. A three-line implementation covers most Latin-script inputs.
What is the slugify npm package?
The `slugify` npm package by simov handles diacritics, custom replacement maps, Unicode transliteration, and special characters across many scripts. Install with `npm install slugify` and call `slugify('My Title', { lower: true })`.
How do I handle special characters in slugs?
Use Unicode normalization (NFD) to decompose characters like 'é' into 'e' + combining accent, then remove the combining mark with the regex `/[\u0300-\u036f]/g`. For non-Latin scripts (Arabic, Chinese), you need transliteration — the `transliteration` npm package handles this.
How do I make a slug URL-safe?
A URL-safe slug contains only lowercase alphanumeric characters and hyphens. After generating a slug, run it through `encodeURIComponent` if it will appear in a URL context. Avoid underscores — Google treats hyphens as word separators but treats underscores as word joiners.
What is the github.com/sindresorhus/slugify package?
It is an ESM-only package that generates URL slugs with Unicode support, a custom character map, and options for separators and case. Install with `npm install @sindresorhus/slugify` (note the scope) and import as an ES module.
All articles · theproductguy.in