Skip to main content

A simple function to slugify a string.

function slugify(str) {
  str = str.toLowerCase()
    .replace(/[^a-z0-9 -]/g, '') // only letters, numbers, space, hyphen
    .replace(/ /g, '-')          // replace spaces with hyphens
    .replace(/[-]{2,}/g, '-')    // remove double+ hyphens
    .replace(/^-|-$/g, '');      // remove leading and or trailing hyphens

  str = str.substr(0, 50);       // limit 50 chars
  return str;
}