How to slugify a string in JavaScript
Tags: javascript, webdev, beginners, node
Published: 2023-04-22 05:47:13

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:

- It consists of lowercase alphanumeric characters (a-z,0-9) and hyphens (-).
- It does not contain any spaces or other special characters.
- It accurately and concisely describes the content of the resource it identifies.
- It is unique within the context of the website or application.

For example, consider the following URL [https://byby.dev/react-data-fetching-libraries](https://byby.dev/react-data-fetching-libraries). In this URL, [react-data-fetching-libraries](https://byby.dev/react-data-fetching-libraries) is the slug that identifies the specific blog post.

## A simple slugify

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:

```js
function slugify(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim leading/trailing white space
  str = str.toLowerCase(); // convert string to lowercase
  str = str.replace(/[^a-z0-9 -]/g, '') // remove any non-alphanumeric characters
           .replace(/\s+/g, '-') // replace spaces with hyphens
           .replace(/-+/g, '-'); // remove consecutive hyphens
  return str;
}

const title = "The Quick Brown Fox Jumps Over The Lazy Dog!";
const slug = slugify(title);
console.log(slug); // "the-quick-brown-fox-jumps-over-the-lazy-dog"
```

## Using a library

There are several libraries available in JavaScript that can be used to slugify a string easily without having to write custom code.

- [lodash](https://lodash.com/) ([56k](https://github.com/lodash/lodash) ⭐) — This library provides a wide range of utility functions for JavaScript, including a `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.

```js
const _ = require('lodash');

const myString = 'Hello World';
const kebabCaseString = _.kebabCase(myString);

console.log(kebabCaseString); // Output: hello-world
```

- [Voca](https://vocajs.com/) ([3.5k](https://github.com/panzerdp/voca) ⭐) — The Voca library offers helpful functions to make string manipulations comfortable: change case, trim, pad, slugify, latinise, sprintf'y, truncate, escape and much more. In Voca, `slugify` is a function that converts a string to a URL-friendly slug format. 

```js
const { slugify } = require('voca');

const myString = 'Hello World!';
const slugifiedString = slugify(myString);

console.log(slugifiedString); // Output: hello-world
```

- [@sindresorhus/slugify](https://github.com/sindresorhus/slugify) ([2.3k](https://github.com/sindresorhus/slugify) ⭐) — Useful for URLs, filenames, and IDs. It handles most major languages, including German (umlauts), Vietnamese, Arabic, Russian, and more.

```js
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
```

- [slugify](https://github.com/simov/slugify) ([1.2k](https://github.com/simov/slugify) ⭐) — This library includes a simple slugify function in vanilla ES2015 JavaScript, has no dependencies, coerces foreign symbols to their English equivalent, works in the browser (window.slugify) and AMD/CommonJS-flavored module loaders.

```js
const slugify = require('slugify');

slugify('some string'); // some-string

// if you prefer something other than '-' as separator
slugify('some string', '_');  // some_string
```

---

## You might also like

- [When to use currying in JavaScript?](https://byby.dev/js-currying)
- [JavaScript `this` binding in common contexts](https://byby.dev/js-this)
- [Unpacking the Magic of Web Minification](https://byby.dev/web-minification)
- [Duck Typing in JavaScript](https://byby.dev/js-duck-typing)
- [JavaScript Source Maps Demystified](https://byby.dev/js-source-maps)