JavaScript Snippet

Convert a String to a URL Slug

Difficulty: Easy

Slugifying turns human titles like `"Côte d'Ivoire, 2025!"` into URL-safe segments like `'cote-d-ivoire-2025'`. Done well, it covers Unicode normalization, accent stripping, and edge punctuation; done poorly, it ships duplicate slugs or 404s. This snippet starts with a regex-only baseline, layers in `normalize('NFD')` for diacritics, and ends with a hardened version that collapses dashes and bounds the length.

Code Snippets
/

Convert a String to a URL Slug

Convert a String to a URL Slug

Slugifying turns human titles like `"Côte d'Ivoire, 2025!"` into URL-safe segments like `'cote-d-ivoire-2025'`. Done well, it covers Unicode normalization, accent stripping, and edge punctuation; done poorly, it ships duplicate slugs or 404s. This snippet starts with a regex-only baseline, layers in `normalize('NFD')` for diacritics, and ends with a hardened version that collapses dashes and bounds the length.

JavaScript
Easy
3 snippets
strings
regex
utility

626 views

18

The simplest correct slugify lowercases the input, replaces every run of non-alphanumeric characters with a single dash, then trims leading and trailing dashes. The character class [a-z0-9] is intentionally narrow so anything we did not anticipate (punctuation, accented letters, emoji) collapses to a separator instead of leaking into the URL. The + quantifier on the negated class is the trick that prevents 'a b' from producing 'a--b'. This baseline is fine for ASCII-only content like English headings or programming keywords.