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
class EventEmitter { constructor() { this.listeners = new Map(); }
Building an EventEmitter in JavaScript
pub-sub
closures
map
Intermediate
7 steps
javascript
const express = require('express'); const compression = require('compression'); const zlib = require('zlib');
Tuning Express response compression
compression
middleware
http
Intermediate
9 steps
javascript
import { NextResponse } from 'next/server' const UPSTREAM = 'https://api.exchangerate.host/latest'
A cached exchange-rate proxy in Next.js
route-handler
caching
revalidation
Intermediate
7 steps
javascript
const logger = require('./logger'); class AppError extends Error { constructor(message, statusCode = 500, details = null) {
Centralized error handling in Express
error-handling
middleware
custom-errors
Intermediate
8 steps
python
import re from django.core.exceptions import ValidationError from django.core.validators import RegexValidator
Building a deconstructible validator in Django
validation
regex
deconstructible
Intermediate
7 steps
javascript
const formatters = new Map(); function getFormatter(locale, currency) { const key = `${locale}:${currency}`;
Caching Intl.NumberFormat for currency formatting
memoization
internationalization
caching
Intermediate
8 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.