javascript 40 lines · 9 steps

Generating URL-safe unique slugs

Turn arbitrary titles into clean, collision-free URL slugs by normalizing text and appending numeric suffixes.

Explained by highlit
1const RESERVED_SLUGS = new Set(['new', 'edit', 'admin', 'api']);
2 
3function slugify(title) {
4 return title
5 .normalize('NFKD')
6 .replace(/[\u0300-\u036f]/g, '')
7 .toLowerCase()
8 .trim()
9 .replace(/[^a-z0-9\s-]/g, '')
10 .replace(/[\s_-]+/g, '-')
11 .replace(/^-+|-+$/g, '');
12}
13 
14function uniqueSlug(title, existingSlugs = new Set()) {
15 let base = slugify(title);
16 
17 if (!base) {
18 base = 'untitled';
19 }
20 
21 if (RESERVED_SLUGS.has(base)) {
22 base = `${base}-1`;
23 }
24 
25 if (!existingSlugs.has(base)) {
26 return base;
27 }
28 
29 let counter = 2;
30 let candidate = `${base}-${counter}`;
31 
32 while (existingSlugs.has(candidate)) {
33 counter += 1;
34 candidate = `${base}-${counter}`;
35 }
36 
37 return candidate;
38}
39 
40export { slugify, uniqueSlug };
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Unicode normalization plus stripping diacritics makes accented titles collapse into plain ASCII slugs.
  2. 2Chaining focused regex replacements keeps each transformation readable and independently correct.
  3. 3Guarding against empty, reserved, and duplicate slugs prevents broken or colliding URLs.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Generating URL-safe unique slugs — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code