Coding Academy / Exercise
Build a predictable URL slug
Turn a title into a readable URL segment and test the edge cases before using it in a link.
You will learn to
- Define a text normalization contract
- Collapse repeated separators
- Explain why a slug is not a unique ID
Before you start
JavaScript strings and regular expressions
Define the output first
A slug is the readable part of a URL, such as first-project in /articles/first-project. In this exercise accept a string, lowercase it, replace every run of characters outside ASCII a–z and 0–9 with one hyphen, then remove leading and trailing hyphens. Return an empty string if there are no supported characters. This deliberately small contract keeps the result predictable.
Trace a title through the pipeline
Start with " My First Project! ". Lowercasing gives " my first project! ". Replacing runs of unsupported characters produces "-my-first-project-". Removing the edge hyphens leaves "my-first-project". The plus quantifier in a regular expression groups consecutive separators: three spaces should not create three hyphens. Preserve digits so "Week 4 Notes" becomes "week-4-notes".
Find collisions before publishing
"Build & Learn" and "Build + Learn" both become "build-learn". A slug describes a title; it does not prove that two records are the same. A real publishing system can attach a stable record ID or check for an existing slug before saving. Changing a published URL also needs a redirect strategy. This exercise only transforms text; it does not create routes or modify records.
Test the boundary and extend deliberately
Try punctuation-only input, an already clean slug, repeated hyphens and an empty string. Our ASCII rule drops accented letters rather than transliterating them and does not support titles in Indian scripts. A multilingual application needs an explicit Unicode URL policy. Do not silently treat this small helper as universal slug generation. Implement slugify below, run the checks, and explain each transformation.
Try it yourself
function slugify(title) {
// Lowercase, replace separator runs, then trim edge hyphens.
return title;
}
console.log(slugify(" My First Project! "));Enable JavaScript for this interactive activity. You can read all lesson explanations above without it.