How to Generate URL Slugs in JavaScript and PHP
Copy-ready slugify functions for JavaScript and PHP that handle accents, symbols and length limits, with notes on uniqueness.
If you build websites or apps, you will eventually need to create slugs in code. Here are reliable starting points for JavaScript and PHP.
JavaScript
function slugify(text, maxLength = 75) {
let slug = text
.normalize('NFKD') // split accented letters
.replace(/[̀-ͯ]/g, '') // remove the accents
.replace(/['’]/g, '') // drop apostrophes
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-') // everything else becomes a hyphen
.replace(/^-+|-+$/g, ''); // trim hyphens
if (slug.length > maxLength) {
slug = slug.slice(0, maxLength + 1);
slug = slug.slice(0, slug.lastIndexOf('-')) || slug.slice(0, maxLength);
}
return slug;
}
slugify("Café Tips & Tricks for Beginners!"); // "cafe-tips-tricks-for-beginners"
PHP
function slugify(string $text, int $maxLength = 75): string {
if (function_exists('transliterator_transliterate')) {
$text = transliterator_transliterate('Any-Latin; Latin-ASCII', $text);
}
$text = str_replace(["'", "\u{2019}"], '', $text);
$text = strtolower($text);
$text = preg_replace('/[^a-z0-9]+/', '-', $text);
$text = trim($text, '-');
if (strlen($text) > $maxLength) {
$cut = substr($text, 0, $maxLength + 1);
$pos = strrpos($cut, '-');
$text = $pos ? substr($cut, 0, $pos) : substr($text, 0, $maxLength);
}
return $text;
}
The transliterator_transliterate function requires PHP's intl extension, which most hosts provide.
Handle special letters
Normalization does not convert every letter. Characters such as ß, æ, ø and ł need a small replacement map (ß to ss, æ to ae, ø to o, ł to l) if you are not using a full transliteration library.
Ensure uniqueness
Before saving, check whether the slug already exists in your database. If it does, append a number: my-post-2, my-post-3. Also add a unique index on the slug column so duplicates can never be saved.
Compare with a reference
Test tricky titles in the slug generator and compare its output with your function's results.
Frequently asked questions
How to generate slugs in JavaScript?
To generate slugs in JavaScript, normalize the text, strip accents, lowercase it, replace non-alphanumeric runs with hyphens and trim hyphens. The slugify in JavaScript function in this guide does exactly that.
How to generate slugs in PHP?
To generate slugs in PHP, transliterate with the intl extension, lowercase, replace non-alphanumeric characters with hyphens and trim. The slugify in PHP function above is a good starting slug function.
Try the free Slug Generator
Turn titles into clean, SEO-friendly URL slugs with bulk mode and smart trimming.
Open Slug Generator