JavaScript: how to create a slug from a string

JavaScript: how to create a slug from a string

In this article, we'll explore how to create a slug from a string using JavaScript.

Slugs are an essential part of creating readable and search engine friendly URLs. A slug is a simplified and clean version of a text string that is used to construct part of a URL. For example, if you have a title like "How to Make a Slug From a String with JavaScript", the corresponding slug might be "how-to-make-slug-from-a-javascript-string". In this article, we'll explore how to create a slug from a string using JavaScript.

The first step in creating a slug is to remove special characters and spaces from the string. This is important because URLs cannot contain spaces or special characters like !, ?, &, etc. We can use regular expressions to remove these characters:

function removeSpecialCharacters(str) {
   return str.replace(/[^\w\s-]/g, '').trim();
}

To ensure consistency and uniformity, it is a good practice to make the string lowercase:

function convertToLowerCase(str) {
   return str.toLowerCase();
}

Spaces in the string should be replaced with dashes to create a human-readable slug. We can do this using the replace method together with a regular expression:

function replaceSpacesWithHyphens(str) {
   return str.replace(/\s+/g, '-');
}

There may be cases where there are multiple consecutive dashes due to previous operations. To make the URL cleaner, we can remove the multiple dashes:

function removeMultipleHyphens(str) {
   return str.replace(/-+/g, '-');
}

Now we can put all these steps together to create our own function that generates the slug:

function createSlug(input) {
   let slug = removeSpecialCharacters(input);
   slug = convertToLowerCase(slug);
   slug = replaceSpacesWithHyphens(slug);
   slug = removeMultipleHyphens(slug);
   return slug;
}

Now that we have created our createSlug function, we can use it to generate slugs from strings:

const title = "How to Create a Slug From a String with JavaScript";
const slug = createSlug(title);
console.log(slug); // Output: "how-to-create-a-slug-from-a-string-with-javascript"