AniUI Academy

Slugify a title for a URL

easyDOM & Utilities+150 XPPractice

Every CMS needs this: the editor types a title, the router needs /blog/build-the-cn-class-merger. Do it inconsistently and you end up with double hyphens, trailing dashes and broken links.

Implement slugify(title) by applying exactly these steps in order: convert the string to lowercase; trim leading and trailing whitespace; replace every run of one or more characters that are not a-z or 0-9 with a single -; finally strip any leading and trailing -.

Because runs collapse to one hyphen, "React 18 & Next.js 14" becomes "react-18-next-js-14". If nothing is left after stripping, return the empty string "".

Arguments

titlestring
The text to slug. Any non-alphanumeric character — spaces, punctuation, symbols — becomes a separator.

Returns

string — A lowercase string of [a-z0-9-] with no leading, trailing or consecutive hyphens. "" when nothing survives.

Examples

slugify("Hello World");
// => "hello-world"

Spaces become a single hyphen and the result is lowercased.

slugify("React 18 & Next.js 14");
// => "react-18-next-js-14"

Runs of punctuation and whitespace collapse to one hyphen.

slugify("---");
// => ""

When nothing alphanumeric remains, the result is the empty string.

What it has to do

  • Lowercase the whole string.
  • Collapse every run of non-alphanumeric characters into exactly one -.
  • Strip leading and trailing hyphens.
  • Return "" when no alphanumeric characters remain.
  • Leave an already-slugged string unchanged.

Notes

  • This slug is ASCII-only: é and other accents are stripped. For international titles you want a Unicode normalisation step (title.normalize("NFKD").replace(/\p{M}/gu, "")) before the character class.
  • Because empty inputs can produce "", routes that use the slug as a URL segment should check for it and fall back to the record id.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.