Skip to content

Instantly share code, notes, and snippets.

@mrfzd
Created March 10, 2023 18:02
Show Gist options
  • Save mrfzd/6f2396f9204aae8250c9eaa184fcfa38 to your computer and use it in GitHub Desktop.
Save mrfzd/6f2396f9204aae8250c9eaa184fcfa38 to your computer and use it in GitHub Desktop.
Generate Safe Slug strig for different purposes
const generateSafeSlugString = (s) => s?.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, "") //remove diacritics
.toLowerCase()
.replace(/\s+/g, '-') //spaces to dashes
.replace(/&/g, '-and-') //ampersand to and
.replace(/[^\w\-]+/g, '') //remove non-words
.replace(/\-\-+/g, '-') //collapse multiple dashes
.replace(/^-+/, '') //trim starting dash
.replace(/-+$/, ''); //trim ending dash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment