JAVASCRIPT

Generate URL-Friendly Slugs from Strings with Regex

Create clean, SEO-friendly URL slugs from any string in JavaScript by transforming text and removing special characters using regex.

function createSlug(text) {
  return text
    .toString()
    .normalize('NFD') // Decompose accented characters
    .replace(/[\u0300-\u036f]/g, '') // Remove diacritics
    .toLowerCase() // Convert to lowercase
    .trim() // Trim whitespace from both ends
    .replace(/[^a-z0-9 -]/g, '') // Replace non-alphanumeric chars
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/-+/g, '-'); // Replace multiple hyphens with a single one
}

// Usage:
// console.log(createSlug("My Awesome Blog Post Title!")); // my-awesome-blog-post-title
// console.log(createSlug("Développeur Web & Mobile")); // developpeur-web-mobile
// console.log(createSlug("Another-Example--With---Many   Spaces")); // another-example-with-many-spaces
How it works: The `createSlug` JavaScript function transforms a given string into a URL-friendly slug. It performs several steps: normalizes Unicode characters, removes diacritics, converts to lowercase, trims whitespace, removes non-alphanumeric characters (except hyphens and spaces), replaces spaces with single hyphens, and consolidates multiple hyphens. This process ensures the resulting string is suitable for use in URLs, making them clean and SEO-friendly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs