JAVASCRIPT
Generate URL-Friendly Slugs
Convert any string into a clean, URL-friendly slug using a JavaScript regular expression, replacing special characters with hyphens for SEO and readability.
function generateSlug(text) {
return text
.toString()
.normalize('NFD') // Decompose combined graphemes
.replace(/[\u0300-\u036f]/g, '') // Remove diacritics
.toLowerCase()
.trim()
.replace(/[^a-z0-9\\s-]/g, '') // Remove all non-word chars except space and hyphen
.replace(/\\s+/g, '-') // Replace spaces with a single dash
.replace(/-+/g, '-'); // Replace multiple dashes with a single dash
}
// Examples
console.log(generateSlug("My Awesome Blog Post Title!")); // "my-awesome-blog-post-title"
console.log(generateSlug("Another post with special characters & numbers 123")); // "another-post-with-special-characters-numbers-123"
console.log(generateSlug(" Article Name with too many spaces ")); // "article-name-with-too-many-spaces"
console.log(generateSlug("Réservé à l'entreprise")); // "reserve-a-lentreprise"
How it works: This JavaScript function transforms a given text into a URL-friendly slug. It first normalizes the string, removes diacritics, converts it to lowercase, and trims whitespace. Crucially, it uses regular expressions to remove unwanted characters, replace spaces with single hyphens, and condense multiple hyphens into one, creating a clean, readable, and SEO-friendly slug for URLs or filenames.