QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Slugify

Verified

Converts a string into a URL-friendly slug, stripping accents and symbols.

  • string
  • slug
  • slugify

Install

npx shadcn@latest add https://quicksnip.dev/r/slugify.json

Code

/**
 * Converts a string into a URL-friendly slug.
 * Strips accents, lowercases, and collapses anything non-alphanumeric into `separator`.
 */
export function slugify(input: string, separator = "-"): string {
  const sep = separator.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return input
    .normalize("NFKD")
    .replace(/[̀-ͯ]/g, "")
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, separator)
    .replace(new RegExp(`^(?:${sep})+|(?:${sep})+$`, "g"), "");
}

Usage

slugify("Crème Brûlée à la mode!"); // "creme-brulee-a-la-mode"
slugify("Hello World", "_");     // "hello_world"