How to create a URL slug from a string
Short answer
A slug is the part of an address made from a title. Convert it to lowercase and replace everything except letters and digits with hyphens:
const slug = 'Hello World: JavaScript Tips!'
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
console.log(slug);Output:
hello-world-javascript-tipsAccented letters
normalize('NFD') splits a letter like é into e and an accent mark, and then the marks are removed:
const slugify = (text) =>
text
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
console.log(slugify('Café au lait in Zürich'));Output:
cafe-au-lait-in-zurichCommon mistake
Without the last replace() the slug may start or end with a hyphen:
console.log(' Hello! '.toLowerCase().replace(/[^a-z0-9]+/g, '-'));Output:
-hello-Functions used in this recipe
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).
- String.prototype.toLowerCase — Converts a string to lowercase.