JavaScript Slug Generator: Vanilla JS, Node.js and Library Solutions
Learn all methods of slug generation in JavaScript. Vanilla JS functions, slugify and limax libraries, React and Vue.js integration.
Slug Generation in JavaScript
Creating slugs in modern web applications is a frequently needed operation on both frontend and backend. In this guide, we'll explore all methods.
Vanilla JavaScript Slug Function
Basic slug function without any library:
function slugify(text) {
return text
.toString()
.normalize('NFD') // Unicode normalization
.replace(/[\u0300-\u036f]/g, '') // Remove accents
.toLowerCase() // Convert to lowercase
.trim() // Trim whitespace
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/[^\w\-]+/g, '') // Remove non-alphanumeric
.replace(/\-\-+/g, '-') // Replace multiple hyphens
.replace(/^-+/, '') // Remove leading hyphens
.replace(/-+$/, ''); // Remove trailing hyphens
}
// Usage
console.log(slugify('Hello World!'));
// Output: hello-worldInternational Character Support
Advanced function for proper character conversion:
function internationalSlugify(text, charMap = {}) {
const defaultMap = {
'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss',
'à': 'a', 'â': 'a', 'é': 'e', 'è': 'e',
'ñ': 'n', 'ç': 'c'
};
const map = { ...defaultMap, ...charMap };
let slug = text.toString();
for (const [key, value] of Object.entries(map)) {
slug = slug.replace(new RegExp(key, 'g'), value);
}
return slug
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-');
}
// Test
console.log(internationalSlugify('Café München'));
// Output: cafe-muenchenNPM Libraries
1. slugify Library
The most popular slug library:
// Installation
npm install slugify
// Usage
import slugify from 'slugify';
const slug = slugify('Hello World', {
lower: true, // Lowercase
strict: true, // Remove special chars
locale: 'en' // English locale
});
console.log(slug); // hello-world
// Custom character replacement
slugify.extend({'€': 'EUR'});
const price = slugify('100€ Price');
console.log(price); // 100eur-price2. limax Library
For multi-language support:
// Installation
npm install limax
// Usage
import slug from 'limax';
// Basic usage
console.log(slug('Hello World')); // hello-world
// Chinese/Japanese
console.log(slug('你好世界')); // ni-hao-shi-jie
// Custom separator
console.log(slug('Hello World', { separator: '_' })); // hello_worldUsing Slugs in React
import { useState, useMemo } from 'react';
import slugify from 'slugify';
function PostForm() {
const [title, setTitle] = useState('');
const slug = useMemo(() => {
return slugify(title, { lower: true, strict: true });
}, [title]);
return (
setTitle(e.target.value)}
placeholder="Title"
/>
);
}Using Slugs in Vue.js
<template>
<div>
<input v-model="title" placeholder="Title" />
<input :value="slug" readonly placeholder="Slug" />
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
import slugify from 'slugify';
const title = ref('');
const slug = computed(() => {
return slugify(title.value, { lower: true, strict: true });
});
</script>Node.js Backend Slugs
// Express.js example
import express from 'express';
import slugify from 'slugify';
const app = express();
app.post('/api/posts', async (req, res) => {
const { title, content } = req.body;
// Generate unique slug
let slug = slugify(title, { lower: true, strict: true });
// Check in database
let counter = 1;
let uniqueSlug = slug;
while (await Post.findOne({ slug: uniqueSlug })) {
uniqueSlug = `${slug}-${counter}`;
counter++;
}
const post = await Post.create({
title,
slug: uniqueSlug,
content
});
res.json(post);
});TypeScript Type Definitions
interface SlugOptions {
separator?: string;
lowercase?: boolean;
strict?: boolean;
locale?: string;
}
function createSlug(text: string, options: SlugOptions = {}): string {
const {
separator = '-',
lowercase = true,
strict = true,
locale = 'en'
} = options;
let slug = text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
if (lowercase) {
slug = slug.toLowerCase();
}
if (strict) {
slug = slug.replace(/[^a-zA-Z0-9\s]/g, '');
}
return slug.trim().replace(/\s+/g, separator);
}Conclusion
There are many options for creating slugs in JavaScript, from vanilla functions to npm libraries. Choose the most suitable method for your project needs.