Slugs are the part of a URL that identifies a particular page on a website. For example, in the URL
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.
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
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
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.
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
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.