Generating Slugs with JavaScript

by Andrew Stewart
published August 31, 2015

I’ve been using a function like this one to generate URL-friendly slugs with JavaScript, and I figured it was likely someone might find it useful.

function slugify(string) {
  return string
    .toString()
    .trim()
    .toLowerCase()
    .replace(/\s+/g, "-")
    .replace(/[^\w\-]+/g, "")
    .replace(/\-\-+/g, "-")
    .replace(/^-+/, "")
    .replace(/-+$/, "");
}

It does the following:

Some examples of it in use:

slugify(12345);
// "12345"

slugify("  string with leading   and   trailing whitespace    ");
// "string-with-leading-and-trailing-whitespace"

slugify("mIxEd CaSe TiTlE");
// "mixed-case-title"

slugify("string with - existing hyphens -- ");
// "string-with-existing-hyphens"

slugify("string with Special™ characters");
// "string-with-special-characters"

Unfortunately, it doesn’t respond as well to non-English characters:

slugify("à, è, ì, ò, ù À, È, Ì, Ò, Ù");
// "" - welp

If you need support for internationalized characters, I recommend finding a more complete solution.