DEV Community

byby.dev
byby.dev

Posted on • Originally published at byby.dev

44 3 3 3 3

How to slugify a string in JavaScript

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. In this URL, 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:

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"
Enter fullscreen mode Exit fullscreen mode

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 (56k ⭐) — 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.
const _ = require('lodash');

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

console.log(kebabCaseString); // Output: hello-world
Enter fullscreen mode Exit fullscreen mode
  • Voca (3.5k ⭐) — 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.
const { slugify } = require('voca');

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

console.log(slugifiedString); // Output: hello-world
Enter fullscreen mode Exit fullscreen mode
  • @sindresorhus/slugify (2.3k ⭐) — Useful for URLs, filenames, and IDs. It handles most major languages, including German (umlauts), Vietnamese, Arabic, Russian, and more.
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
Enter fullscreen mode Exit fullscreen mode
  • slugify (1.2k ⭐) — 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.
const slugify = require('slugify');

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

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

You might also like

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (4)

Collapse
 
tracygjg profile image
Tracy Gilmore

Hi Byby,

Was there a reason you used str.replace(/^\s+|\s+$/g, '') rather than using the built-in String.trim() method?

Regards, Tracy

Collapse
 
bybydev profile image
byby.dev

Not at all, I just prefer using regex consistently.

Collapse
 
tracygjg profile image
Tracy Gilmore

Byby, I am a fan of using Regular Expressions but they can be less performant than other options. For instance, using the + symbol to select one or more instances is very open-ended. An alternative, more performant approach might be to replace + with {1,n} where, n is the greatest number of characters you can reasonably expect, there is usually an upper limit. In this case, determining a value for n might be difficult (which demonstrates the problem) so using trim would be a better option.

Collapse
 
jwilliams profile image
Jessica williams

In JavaScript, you may combine string manipulation and regular expressions to slugify a string. Here is an illustration of a function that turns a string into a slug:

function slugify(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces
str = str.toLowerCase(); // convert to lowercase
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by "-"
.replace(/-+/g, '-'); // collapse dashes
return str;
}

The following is done by this function:

uses replace() to remove any leading or trailing spaces from the string.

Use toLowerCase() to change the string's case to lowercase.

Uses a regular expression to remove all characters that aren't letters, numbers, spaces, or dashes (/[a-z0-9 -]/g). The g flag instructs the computer to replace every instance, not just the first.

Any whitespace characters (spaces, tabs, and newlines) are combined into a single space, which is then replaced with a dash (-) using the function replace(/s+/g, '-').
Use replace(/-+/g, '-') to combine any consecutive dashes into a single dash.

Here is an illustration of how to use the slugify() function:

const title = "How to slugify a string in JavaScript";
const slug = slugify(title); // "how-to-slugify-a-string-in-javascript"
console.log(slug);

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs