JavaScript: How to Convert a String to a URL Slug

Updated: February 20, 2023 By: Khue Post a comment

In the world of web development, a slug is a URL-friendly version of a string, typically used in URLs to identify a specific page or resource. A slug usually consists of lowercase characters, numbers, and hyphens (or underscores), with any spaces or special characters replaced by hyphens (or underscores).

This article walks you through 3 examples of converting a string to a slug in JavaScript (these examples are different from each other).

Using Regular Expressions

This example works well with English and languages similar to English. We will define a function called stringToSlug that uses simple regular expressions to replace any spaces and any non-word characters (such as special characters or punctuation) with hyphens. We also use the replace() method with the regular expression /[\W_]+/g to reduce any consecutive hyphens to a single hyphen.

We also use the trim() method to remove any leading or trailing whitespace, as well as the toLowerCase() method to convert the string to lowercase.

The code:

const stringToSlug = (str) => {
  return str
    .trim()
    .toLowerCase()
    .replace(/[\W_]+/g, '-')
    .replace(/^-+|-+$/g, '');
};

console.log(stringToSlug('Welcome to Sling Academy!'));
console.log(stringToSlug('  Puppy nad cat are best friends!@@@   '));

Output:

welcome-to-sling-academy
puppy-nad-cat-are-best-friend

Handling International Characters

Working with non-English strings can be tough. In the example below, we will use the normalize() method to decompose any diacritical marks and then remove them with a regular expression. We will also replace any non-word characters with hyphens and convert the string to lowercase. The function toSlugAdvanced() in the example can produce a slug that is URL-friendly and compatible with a wide range of character sets.

The code:

const toSlugAdvanced = (str) => {
  return str
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[\W_]+/g, '-')
    .toLowerCase()
    .replace(/^-+|-+$/g, '');
}

console.log(
  toSlugAdvanced('This is an Advanced Example: 漢字, ñ, é, ü, î, ā, ă!')
);

Output:

this-is-an-advanced-example-n-e-u-i-a-a

Using Lodash

Lodash is a popular JavaScript library that provides a wide range of utility functions, including one called kebabCase(), which automatically converts a string to kebab-case (lowercase with hyphens). We also use a little regular expression to refine the result.

Install Lodash:

npm i lodash

Example:

import _ from 'lodash';

const stringToSlug = (str) => {
  return _.kebabCase(str.replace(/[\W_]+/g, '-'));
}

console.log(stringToSlug('Welcome to Sling Academy & ^ !@@@ 猫狗和龙!'));

Output:

welcome-to-sling-academy

That’s it. If you have any questions, please leave a comment. Happy coding and have a nice day!