Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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-tips

Accented 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-zurich

Common 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

Thanks for reading!

Donate to the site — we work hard for you.