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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Unicode normalization plus stripping diacritics makes accented titles collapse into plain ASCII slugs.
- 2Chaining focused regex replacements keeps each transformation readable and independently correct.
- 3Guarding against empty, reserved, and duplicate slugs prevents broken or colliding URLs.
Related explainers
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/generating-url-safe-unique-slugs-explained-javascript-c3fd/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.