Files
30-seconds-of-code/snippets/slugify.md
Angelos Chalaris 68dd9e2966 Update slugify.md
2020-10-04 10:36:38 +03:00

525 B

title, tags
title tags
slugify string,regexp,intermediate

Converts a string to a URL-friendly slug.

  • Use String.prototype.toLowerCase() and String.prototype.trim() to normalize the string.
  • Use String.prototype.replace() to replace spaces, dashes and underscores with - and remove special characters.
const slugify = str =>
  str
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');
slugify('Hello World!'); // 'hello-world'