JavaScript

Slugify String

by @admin
10h ago
Apr 28, 2026
Public
Converts any string into a URL-safe slug: lowercases it, replaces accented characters with ASCII equivalents, strips all non-alphanumeric characters (except hyphens), and collapses multiple hyphens into one. Ideal for generating URL slugs from blog titles, product names, or user input.
JavaScript
function slugify(str) {
  return str
    .normalize('NFD')                     // decompose accented chars
    .replace(/[̀-ͯ]/g, '')      // strip accent marks
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '')        // remove non-alphanumeric
    .replace(/[\s]+/g, '-')              // spaces → hyphens
    .replace(/-+/g, '-');                // collapse multiple hyphens
}

// Usage
console.log(slugify('Hello World!'));           // hello-world
console.log(slugify('  Über Café  '));          // uber-cafe
console.log(slugify('10 Reasons to Use JS'));   // 10-reasons-to-use-js
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.