Generating Slugs with JavaScript

2015-08-31

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:

  • converts input to a string
  • trims trailing whitespace
  • converts strings to lowercase
  • replaces any spaces with - (hyphen)
  • removes any non-word, non-hyphen characters
  • converts multiple hyphens to a single one
  • ensures hyphens don’t appear at the start or end of the string

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.