SlugifyLoading saved progress…

Slugify

A slug is the URL-safe version of a title — lowercase, hyphen-separated, and reduced to just letters, digits, and single hyphens (the my-post-title you see in a blog URL or a docs anchor). Write slugify(str) that turns any string into one: "Hello, World!" becomes "hello-world" and "Café Crème" becomes "cafe-creme". The work is in the messy inputs — accented letters, punctuation, and stray or repeated spaces — each of which needs its own cleanup step.

Signature

slugify(str)
// str: any string — a title, heading, or filename
// returns: a slug containing only [a-z0-9-], with no
//   leading, trailing, or doubled hyphens

Examples

slugify('Hello, World!');         // 'hello-world'
slugify('  Multiple   Spaces  '); // 'multiple-spaces'
slugify('Node.js & React');       // 'node-js-react'
slugify('Top 10 Tips');           // 'top-10-tips'
slugify('Café Crème');   // 'cafe-creme'   (accents stripped)
slugify('Crème Brûlée'); // 'creme-brulee'
slugify('!!! ??? ...');  // ''             (all symbols → empty)
slugify('');             // ''

Notes

  • Lowercase only. The output uses az, 09, and -. No uppercase, no spaces, no punctuation.
  • Accents become their base letter. é becomes e and ü becomes u, so "Zürich" slugs to "zurich". That means normalizing Unicode, not a hand-written lookup table.
  • Collapse, do not multiply. A whole run of non-alphanumeric characters (spaces, punctuation, symbols) becomes a single hyphen — "a & b" is "a-b", never "a---b".
  • No hyphens on the ends. Trim any leading or trailing hyphens, so "--Hello--" is "hello".
  • Digits stay. Numbers are alphanumeric and survive: "Top 10" keeps its 10.
  • Empty is a valid answer. A string with no letters or digits (all spaces or symbols) slugs to "".

FAQ

How does slugify handle accented characters like é?
It normalizes the string to NFD, which splits an accented letter into its base letter plus a separate combining mark, then removes the combining marks. So é becomes e and the letter survives the later alphanumeric filter.
Why does slugify lowercase the string before removing non-alphanumeric characters?
The filter keeps only [a-z0-9], which treats uppercase A–Z as non-alphanumeric. Lowercasing first means the letters survive; skip it and every capital letter would be replaced with a hyphen.
What does slugify return for an empty or all-symbol string?
An empty string. A title made only of spaces or punctuation collapses to a single hyphen, which the final edge-hyphen trim then removes, leaving nothing behind.
Loading editor…