Slugify Your Article Names with TS/JS

Need to create neat, clean URLs for your articles or blog posts?

Today, we're diving into slugification (yes, that's a word now).

An Extra Problem: Duplicate Slugs

Picture this: you've got two brilliant articles titled "10 TypeScript Tips" and "10 TypeScript Tricks".

Slugify them, and what do you get? 10-typescript-tips and 10-typescript-tricks.

But what if you have another "10 TypeScript Tips" article?

Boom! Collision time, population: your website's routing system. That's why I like to add a short ID to the end of my slugs. You'll notice it at the end of every Codú article's URL.

Here's how we do it:

The Solution:

First things first, I use Nano ID because it's a tiny package that is flexible for creating IDs of any size.

npm install nanoid

It's lean, mean, and generates unique IDs faster than you can say "TypeScript rocks" or some other cringe worthy statement...

The Code

Alright, let's dive into the good stuff:

import { customAlphabet } from 'nanoid';

// Create a custom nanoid function with lowercase letters and numbers
const generateId = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 5);

function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^\w\s-]/g, '') // Remove non-word chars (except spaces and hyphens)
    .replace(/\s+/g, '-')     // Replace spaces with hyphens
    .replace(/--+/g, '-')     // Replace multiple hyphens with single hyphen
    .trim();                  // Trim leading/trailing spaces and hyphens
}

function generateUniqueSlug(articleName: string): string {
  const baseSlug = slugify(articleName);
  const uniqueId = generateId(); // Generate a 5-character ID
  return `${baseSlug}-${uniqueId}`;
}

// Example usage
const articleName = "10 Tips for Writing Great TypeScript Code!";
const uniqueSlug = generateUniqueSlug(articleName);
console.log(uniqueSlug);
// Output is something like: 10-tips-for-writing-great-typescript-code-en32x

We're using customAlphabet from nanoid to create IDs using only lowercase letters and numbers. Why? Because we're keeping it URL-friendly, folks!

And then the slugify function. This turns your article title into a beautiful "slug".

generateUniqueSlug is what ties it all together. It slugifies your title and then adds a 5-character unique ID at the end. It's like giving each slug its own little name tag.

Run this code, and voilà! Your "10 Tips for Writing Great TypeScript Code!" turns into something like:

10-tips-for-writing-great-typescript-code-a7b3c

Now, you can have as many "10 Tips" articles as you like, and they'll all have unique URLs!

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.