Published: July 07 2023

Vanilla JS - Slugify a String in JavaScript

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.

The function performs the following steps:

  1. Converts to lower case and trims any leading or trailing spaces.
  2. Removes any accents from characters (e.g. á, â, â, ã, ä, å, ç).
  3. Replaces any other special characters with spaces.
  4. Replaces multiple spaces or dashes (hyphens) with a single dash.
function slugify(input) {
    if (!input)
        return '';

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

    // remove accents from charaters
    slug = slug.normalize('NFD').replace(/[\u0300-\u036f]/g, '')

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

    // replace multiple spaces or hyphens with a single hyphen
    slug = slug.replace(/[\s-]+/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.

(See on StackBlitz at https://stackblitz.com/edit/vanilla-js-slugify)

 


Need Some Vanilla JS Help?

Search fiverr for freelance Vanilla JS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by