Slugify a title for a URL
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 "".
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.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.