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 "".
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.
- 1.lowercases and hyphenates words
- 2.trims whitespace and drops punctuation
- 3.collapses runs of symbols into one hyphen
- 4.returns an empty string when nothing survives
- 5.leaves an already slugged string alone
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.