JAVASCRIPT

Generate a URL-Friendly Slug from a String

Create clean, SEO-friendly slugs for URLs from any given string by converting to lowercase, replacing spaces, and removing special characters using regex.

function generateSlug(text) {
  text = text.toString().normalize('NFD').replace(/[̀-ͯ]/g, ''); // Remove diacritics
  text = text.toLowerCase(); // Convert to lowercase
  text = text.replace(/[^a-z0-9\s-]/g, ''); // Remove non-alphanumeric characters (except spaces and hyphens)
  text = text.replace(/\s+/g, '-'); // Replace spaces with a single hyphen
  text = text.replace(/-+/g, '-'); // Replace multiple hyphens with a single hyphen
  text = text.trim('-'); // Trim hyphens from start/end
  return text;
}

// Example Usage:
console.log(generateSlug("My Awesome Article Title 123!@#")); // "my-awesome-article-title-123"
console.log(generateSlug("Another Title with Special Chars & numbers ٤٥٦")); // "another-title-with-special-chars-numbers-456"
console.log(generateSlug("  A Title with    extra   spaces  ")); // "a-title-with-extra-spaces"
How it works: This JavaScript function transforms a string into a URL-friendly slug. It normalizes characters (removing accents), converts to lowercase, removes most special characters, replaces spaces with hyphens, consolidates multiple hyphens, and trims leading/trailing hyphens, all using a series of regular expression replacements.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs