Files
30-seconds-of-code/js/s/slugify.md
Angelos Chalaris 5c913d20bd Reorganize snippets
2023-05-03 21:19:02 +03:00

619 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
String to slug snippet javascript
string
regexp
houses-rock-sea 2020-10-04T10:36:38+03:00

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'