Vanilla JS - Slugify a String in JavaScript

·

1 min read

It's a pretty common requirement to convert a string into a slug for things like URL paths with SEO friendly titles.

A slug is typically all lower case, separated by dashes (hyphens) instead of spaces and doesn't contain any special characters.

JS Slugify Function

This is a little JavaScript slugify function I wrote recently to auto-generate a slug from a title text field. But it could be used to convert any string into a slug.

function slugify(input) {
  if (!input) return '';

  // 1. make lower case and trim
  var slug = input.toLowerCase().trim();

  // 2. remove accents from charaters (e.g. á, â, â, ã, ä, å, ç)
  slug = slug.normalize('NFD').replace(/[\u0300-\u036f]/g, '');

  // 3. change đĐ chars because it does not remove in Step 2
  slug = slug.replace(/[đĐ]/g, 'd');

  // 4. replace invalid chars
  slug = slug.replace(/[^a-z0-9\s-]/g, '');

  // 5. replace multiple spaces or hyphens with a single hyphen
  slug = slug.replace(/[\s-]+/g, '-');

  // 6. removes - at begin & end
  slug = slug.replace(/^-+|-+$/g, '');

  return slug;
}

StackBlitz Demo

Here's a demo of the slugify function in action on StackBlitz. The slug field is auto generated as you type a string into the title field.