Skip to content

Instantly share code, notes, and snippets.

@abdelfattahradwan
Last active April 16, 2024 20:52
Show Gist options
  • Save abdelfattahradwan/10dc8d5fcb90b949cdc01d15fd0dc707 to your computer and use it in GitHub Desktop.
Save abdelfattahradwan/10dc8d5fcb90b949cdc01d15fd0dc707 to your computer and use it in GitHub Desktop.
A function that converts strings into URL-friendly slugs by lowercasing, replacing non-alphanumeric characters with dashes, and trimming leading/trailing dashes.
const NON_ALPHANUMERIC_REGEX = /[^a-z0-9]+/g;
const LEADING_TRAILING_DASHES_REGEX = /^-+|-+$/g;
export default function slugify(title: string): string {
return title
.toLowerCase()
.replace(NON_ALPHANUMERIC_REGEX, "-")
.replace(LEADING_TRAILING_DASHES_REGEX, "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment