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

function slugify(str) {
    return str
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '');
}

console.log(slugify('Hello World!'));           // hello-world
console.log(slugify('Top 10 JS Tips'));         // top-10-js-tips
console.log(slugify('  spaces  &  symbols  ')); // spaces-symbols

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.