WebTuts - seomat.com

Your ultimate destination for comprehensive, easy-to-follow web tutorials.

Slugify a string in JavaScript

Converting a string into a slug typically involves replacing spaces with hyphens, removing special characters, and converting all letters to lowercase.

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.