Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Generating slugs using one line of code in JavaScript

Slugs are the part of a URL that identifies a particular page on a website. For example, in the URL https://www.google.com/search?q=javascript, the slug is search. It is also known as the URL segment or the permalink.

Many times, you might have seen that the slugs are generated automatically by the CMS or the blogging platform you are using. For example, in WordPress, the slugs are generated automatically based on the title of the post. Similarly, in Ghost, the slugs are generated automatically based on the title of the post.

But sometimes, you might want to generate the slugs yourself. For example, you might want to generate the slugs for your static website. In such cases, you can use the following one-liner to generate the slugs in JavaScript. You don’t need to use any external library for this.

Generating slugs

The following one-liner can be used to generate the slugs.

const slugify = (str) => str.toLowerCase()
                            .replace(/[^a-z0-9]+/g, '-')
                            .replace(/(^-|-$)+/g, '');

Let’s understand what’s going on here.

First, we are converting the given string to lowercase using the toLowerCase() method.

Next, we are replacing all the non-alphanumeric characters with a hyphen using the replace() method with the specified regex.

Finally, we are removing the hyphens, spaces, and other non-alphanumeric characters from the beginning and the end of the string using the second replace() method.

Usage

You can use the above one-liner to generate the slugs for your static website or any other use case for that matter.

For example, you can use it to generate the slugs for your blog posts like so.

const title = 'Generating slugs with one line of code using JavaScript';

console.log(slugify(title));
// output: generating-slugs-with-one-line-of-code-using-javascript

This even works fine with strings that contain special characters like so.

const title = 'Yo, Hello world!';

console.log(slugify(title));
// output: yo-hello-world

Demo?

I built a simple app around this.

Text to Slug

Quirks

Of course, there are some quirks with the above one-liner. For example, it doesn’t work well with strings that contain non-English and accented characters. But for most of the use cases, it should work fine.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?