I recently created a small JavaScript function for slugifying, which automatically generates slugs from title text fields. However, it has the potential to convert any string into a slug.
const createSlug = (string) => {
if (!string) return '';
// lower case the string and trim the spaces
let slug = string.toLowerCase().trim();
// replace special chars from string
slug = slug.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
// replace invalid chars with spaces
slug = slug.replace(/[^a-z0-9\s-]/g, ' ').trim();
// replace unwanted spaces or hyphens with a single hyphen
slug = slug.replace(/[\s-]+/g, '-');
return slug;
}
This function first converts the string to lowercase, then uses regular expressions to remove special characters and replace spaces with hyphens. Finally, it removes any leading or trailing hyphens to generate a clean slug.
Demo
See the Pen Slugify a string in JavaScript by Stanescu Eduard-Dan (@ZsharE) on CodePen.