Skip to content
GreenSnippets

Slugify a string for URLs

Convert any title into a lowercase, hyphenated, accent-free slug that is safe to use in a URL.

JavaScript
function slugify(text, maxLength = 80) {
  return text
    .normalize("NFKD")
    .replace(/[̀-ͯ]/g, "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, maxLength)
    .replace(/-+$/g, "");
}

Example / expected output

Output
slugify("Crème Brûlée: the 5-minute recipe!") // "creme-brulee-the-5-minute-recipe"

How it works

Unicode normalization (NFKD) splits accented letters into a base letter plus a combining mark, which the regex then removes. Everything that is not a letter or digit becomes a single hyphen, and leading or trailing hyphens are trimmed. Check uniqueness in your database separately.