A slug is a string that is used to uniquely identify a resource in a URL-friendly way. It is typically used in the URL to identify a specific page or post on a website. A slug consists of a set of characters that are easy to read and remember, and that accurately describe the content of the resource.
A string can be qualified as a slug if it meets the following criteria:
For example, consider the following URL https://byby.dev/react-data-fetching-libraries. In this URL, react-data-fetching-libraries is the slug that identifies the specific blog post.
In JavaScript, you can slugify a string by converting it to a URL-friendly format where any special characters and spaces are replaced with hyphens or underscores. Here’s an example function that can accomplish this:
function slugify(str) {
return String(str)
.normalize('NFKD') // split accented characters into their base characters and diacritical marks
.replace(/[\u0300-\u036f]/g, '') // remove all the accents, which happen to be all in the \u03xx UNICODE block.
.trim() // trim leading or trailing whitespace
.toLowerCase() // convert to lowercase
.replace(/[^a-z0-9 -]/g, '') // remove non-alphanumeric characters
.replace(/\s+/g, '-') // replace spaces with hyphens
.replace(/-+/g, '-'); // remove consecutive hyphens
}
console.log(slugify("The Quick Brown Fox Jumps Over The Lazy Dog! "))
// "the-quick-brown-fox-jumps-over-the-lazy-dog"
console.log(slugify("söme stüff with áccènts"))
// "some-stuff-with-accents"
There are several libraries available in JavaScript that can be used to slugify a string easily without having to write custom code.
kebabCase
function that can be used to convert a string to kebab case, which is similar to slug format. Kebab case format is a naming convention where words are separated by a hyphen (-) and all letters are in lower case.const _ = require('lodash');
const myString = 'Hello World';
const kebabCaseString = _.kebabCase(myString);
console.log(kebabCaseString); // Output: hello-world
slugify
is a function that converts a string to a URL-friendly slug format.const { slugify } = require('voca');
const myString = 'Hello World!';
const slugifiedString = slugify(myString);
console.log(slugifiedString); // Output: hello-world
const slugify = require('@sindresorhus/slugify');
slugify('I ♥ Dogs'); // i-love-dogs
slugify(' Déjà Vu! '); // deja-vu
slugify('fooBar 123 $#%'); // foo-bar-123
slugify('я люблю единорогов'); // ya-lyublyu-edinorogov
slugify('BAR and baz', {separator: '_'}); // bar_and_baz
slugify('BAR and baz', {separator: ''}); // barandbaz
const slugify = require('slugify');
slugify('some string'); // some-string
// if you prefer something other than '-' as separator
slugify('some string', '_'); // some_string