JAVASCRIPT
Generate URL-Friendly Slugs from Strings
Discover how to transform any string into a clean, URL-friendly slug by lowercasing, replacing spaces, and removing special characters with regex.
function createSlug(text) {
return text
.toString()
.normalize('NFD') // Decompose accented characters
.replace(/[\u0300-\u036f]/g, '') // Remove diacritics
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, '') // Remove invalid chars
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/-+/g, '-'); // Collapse multiple dashes
}
// Examples:
console.log(createSlug('My Awesome Article Title! 🎉')); // "my-awesome-article-title"
console.log(createSlug('Crème brûlée (Delicious)')); // "creme-brulee-delicious"
How it works: This snippet provides a utility function `createSlug` that converts a given string into a URL-friendly slug. It uses a series of string manipulations and regular expressions to achieve this: normalizing characters to remove diacritics, lowercasing, trimming whitespace, removing non-alphanumeric characters (except hyphens and spaces), replacing spaces with single hyphens, and finally collapsing multiple hyphens into one. This is essential for creating clean and readable URLs for articles, products, or categories.