2026-03-11•2 min read•by DevUtilz
URL Slug Generator for SEO
SlugSEOURLTools
URL Slug Generator for SEO
A slug is the part of the URL that identifies a page. Good slugs improve SEO and readability.
What is a Slug?
URL: https://example.com/blog/how-to-learn-javascript
Slug: how-to-learn-javascript
Creating Slugs
function createSlug(text) {
return text
.toLowerCase() // Convert to lowercase
.trim() // Remove whitespace
.replace(/[^\w\s-]/g, '') // Remove special chars
.replace(/[\s_-]+/g, '-') // Replace spaces with -
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}
// Example
createSlug('How to Learn JavaScript!')
// 'how-to-learn-javascript'
Using Libraries
// slugify npm package
import slugify from 'slugify';
slugify('Hello World'); // 'hello-world'
// With options
slugify('Hello World', {
lower: true,
strict: true, // removes special chars
trim: true
});
Handling Unicode
function slugifyUnicode(text) {
// Use transliteration for non-latin characters
const transliterated = text
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, ''); // Remove diacritics
return createSlug(transliterated);
}
// Example
slugifyUnicode('Über uns'); // 'uber-uns'
SEO Best Practices
| Do | Don't | |----|-------| | Use descriptive words | Use IDs or numbers | | Keep it under 60 chars | Make it too long | | Use hyphens for spaces | Use underscores | | Include target keyword | Repeat keywords | | Make it readable | Use random characters |
Handling Duplicates
async function createUniqueSlug(title, existingSlugs) {
let slug = createSlug(title);
let counter = 1;
while (existingSlugs.includes(slug)) {
slug = `${createSlug(title)}-${counter}`;
counter++;
}
return slug;
}
Common Patterns
// From title
slugify('10 Tips for Better Code');
// '10-tips-for-better-code'
// Remove numbers at start
slugify('2024 Guide to Web Development')
.replace(/^\d+-/, '');
// 'guide-to-web-development'
// Keep numbers for dates
slugify('January 2024 Update');
// 'january-2024-update'
Database Storage
// Store slug in database
const post = {
title: 'My Blog Post',
slug: slugify('My Blog Post') // 'my-blog-post'
};
// Query by slug
const post = await db.posts.findOne({ slug: 'my-blog-post' });
Generating from Content
function generateSlugFromContent(content) {
// Get first meaningful text
const text = content
.replace(/#\s/g, '') // Remove headings marker
.replace(/\n/g, ' ') // Newlines to spaces
.substring(0, 100); // Take first 100 chars
return slugify(text);
}
Conclusion
Use slugify with proper options. Keep slugs short, readable, and descriptive. Handle duplicates to avoid conflicts. Include target keywords naturally.