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
javascript
import { useCallback, useState } from "react"; const MIN = 0; const MAX = 1000;
Building a dual-thumb price slider in React
controlled-components
state-clamping
usecallback
Intermediate
8 steps
javascript
class LyricsSync { constructor(audio, container, lines) { this.audio = audio; this.container = container;
Building a synced lyrics highlighter
binary-search
dom-manipulation
event-handling
Intermediate
9 steps
javascript
const express = require('express'); const app = express();
Enforcing HTTPS with Express middleware
middleware
https
security
Intermediate
6 steps
typescript
type TokenType = "keyword" | "string" | "comment" | "number" | "text"; interface Token { type: TokenType;
How a regex tokenizer highlights code
tokenizer
regex
lexing
Intermediate
10 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 steps
java
public final class LogRedactor { private static final Pattern SECRET = Pattern.compile( "(?i)(password|token|api[_-]?key|secret|authorization)\\s*[=:]\\s*\\S+");
Streaming log redaction in Java
regex
streaming-io
try-with-resources
Intermediate
9 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.