Slugify a string for a URL in JavaScript
Intermediate · 4 min read
Look at the address of almost any blog post and you will see something like /blog/hello-world. That last part is a slug: the title turned into lowercase words joined by dashes, with no spaces, punctuation or accents. Slugs make addresses readable, easy to share and friendly to search engines.
In this tutorial you will write slugify, which turns 'Hello, World!' into 'hello-world'. Along the way you will fold accents, squash runs of punctuation into one dash and trim dashes off the ends. You should know toLowerCase and the basics of replace with a regex. Each pattern is explained below.
The plan
A slug is built as a chain of small clean-up steps, each passing its result to the next:
- Split accents off their letters and drop them, so
ébecomese. - Lowercase everything.
- Replace every run of characters that are not letters or digits with a single dash.
- Remove any dash left at the start or end.
Runs, not single characters
In a regex, + means "one or more of the thing before me". So [^a-z0-9]+ matches a whole run of unwanted characters in one go, such as , (a comma and a space) or &, and replaces the entire run with one dash. Without the +, each character would get its own dash.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
48 Slugify a heading for a URL
fairTurn 'Hello, World!' into 'hello-world'. Fold accents, collapse runs of punctuation into one dash, and leave no dash at either end.
Stuck? Three hints, smallest first
- 1. Fold the accents first, with NFD and a mark strip.
- 2. Replace a run of unwanted characters with one dash, not each character.
- 3. Then trim the dashes off both ends, and decide what to do when nothing is left.
Step 1: fold the accents
const folded = 'Café Déjà Vu'.normalize('NFD').replace(/\p{M}/gu, '');
console.log(folded); // 'Cafe Deja Vu'
normalize('NFD') splits each accented letter into its base letter plus a separate accent mark. \p{M} matches any accent mark, and the u flag turns on that Unicode pattern. Removing the marks leaves plain letters. Exercise 44 covers this in detail.
Step 2: lowercase
console.log('Cafe Deja Vu'.toLowerCase()); // 'cafe deja vu'
Lowercasing before the next step matters, because the next pattern only keeps a to z.
Step 3: one dash per run, the natural wrong turn first
const text = 'c++ & c#';
console.log(text.replace(/[^a-z0-9]/g, '-')); // 'c-----c-'
console.log(text.replace(/[^a-z0-9]+/g, '-')); // 'c-c-'
Without +, every plus sign, space, ampersand and hash becomes its own dash. With +, each run of them collapses into one. Much better, but there is still a dash at the end, left by the #.
Step 4: trim the dashes off the ends
console.log('c-c-'.replace(/^-+|-+$/g, '')); // 'c-c'
console.log('-spaced-out-'.replace(/^-+|-+$/g, '')); // 'spaced-out'
^-+ means "dashes at the very start" and -+$ means "dashes at the very end". The | means "or". This step has to come after Step 3, because Step 3 is what creates the stray dashes.
Step 5: chain it all together
function slugify(text) {
return text
.normalize('NFD')
.replace(/\p{M}/gu, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
console.log(slugify('Hello, World!')); // 'hello-world'
console.log(slugify('C++ & C#')); // 'c-c'
console.log(slugify(' Spaced Out ')); // 'spaced-out'
console.log(slugify('Café Déjà Vu')); // 'cafe-deja-vu'
console.log(slugify('2025 Q1 Report')); // '2025-q1-report'
Each method returns a new string, so they can be chained one per line. Digits survive because the pattern keeps 0-9.
Step 6: slugify twice, get the same thing
function slugify(text) {
return text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase()
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
}
console.log(slugify(slugify('Hello, World!'))); // 'hello-world'
A slug run through slugify again doesn't change. That property has a name, idempotent, and it matters: if saving a post twice changed its slug, every link to it would break.
Step 7: when nothing is left
function slugify(text) {
return text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase()
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
}
console.log(JSON.stringify(slugify('---'))); // ""
console.log(slugify('---') || 'untitled'); // 'untitled'
console.log(JSON.stringify(slugify('Лагос'))); // ""
A title made only of punctuation slugs to an empty string. So does a title in Cyrillic, Greek, Arabic or Chinese, because [^a-z0-9] throws away every letter outside a to z. An empty slug would give a broken address, so always have a fallback. || uses the right side when the left is an empty string.
If your titles aren't all in English letters, keep any letter or number instead. \p{L} means "any letter" and \p{N} means "any number":
console.log('Лагос'.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-')); // 'лагос'
The full solution
The panel has slugify and prints four example headings, including the Cyrillic one that disappears. Press Run, then read the checks underneath.
function slugify(text) {
return text
.normalize('NFD') // split accents off their letters
.replace(/\p{M}/gu, '') // and drop the marks
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-') // any RUN of other characters becomes one dash
.replace(/^-+|-+$/g, ''); // no leading or trailing dash
}
console.log("'Hello, World!' ->", slugify('Hello, World!'));
console.log("'C++ & C#' ->", slugify('C++ & C#'));
console.log("'Café Déjà Vu' ->", slugify('Café Déjà Vu'));
console.log("'Лагос' ->", JSON.stringify(slugify('Лагос')), '<- everything filtered away');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the classic example', slugify('Hello, World!'), 'hello-world');
test('a run of punctuation and space collapses to one dash', slugify('C++ & C#'), 'c-c');
test('leading and trailing dashes are trimmed', slugify(' Spaced Out '), 'spaced-out');
test('accents are folded to their base letters', slugify('Café Déjà Vu'), 'cafe-deja-vu');
test('digits survive', slugify('2025 Q1 Report'), '2025-q1-report');
test('a slug is already a slug, so it is idempotent', slugify(slugify('Hello, World!')), 'hello-world');
test('a heading of only punctuation slugs to nothing', slugify('---'), '');
test('which is why an empty slug needs a fallback', slugify('---') || 'untitled', 'untitled');
test('a non-Latin heading is DESTROYED by the a-z filter', slugify('Лагос'), '');
test('so filter on the letter category instead when that matters', 'Лагос'.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-'), 'лагос');
Two decisions are doing the work. Replacing a run rather than each character is why 'C++ & C#' is 'c-c' and not 'c-----c-'. And trimming the dashes last, after the replacement, is why a trailing '!' does not leave one behind.
The [^a-z0-9] filter is an English assumption. It deletes Cyrillic, Greek, Arabic and CJK entirely, giving an empty slug — so a fallback is not optional, it is the difference between a URL and a 404. If your headings are not all Latin, filter on \p{L} and \p{N} and let the URL carry percent-encoded characters.
Idempotence is worth asserting on any normalising function. If f(f(x)) !== f(x), re-saving a record changes its slug and breaks every existing link.
Common mistakes
- Leaving out the
+. Each punctuation character gets its own dash, so you getc-----c-. Match runs. - Trimming dashes before replacing. The replacement creates new dashes at the ends. Trim last.
- No fallback for an empty slug. A title of only symbols, or in a non-Latin script, gives
''. Useslug || 'untitled'.
Try it yourself
- Use
slugifyon"Don't Stop Me Now"and decide whetherdontordon-tis better. Change the code to get the one you prefer. - Make two posts called
'Hello'get the slugs'hello'and'hello-2'. - Limit a slug to 30 characters without leaving a dash at the end.