JAVASCRIPT

Generate URL-Friendly Slug from String

Learn to convert any string into a clean, URL-friendly slug using regular expressions, ideal for SEO and user-readable links.

function createSlug(text) {
  return text
    .toString()
    .normalize('NFD') // Decompose accented characters
    .replace(/\p{M}/gu, '') // Remove diacritics
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '') // Remove invalid chars
    .replace(/\s+/g, '-') // Replace spaces with -
    .replace(/-+/g, '-'); // Replace multiple - with single -
}

// Example usage:
const title = "My Awesome Article Title with Special Chars & numbers 123! éàü";
const slug = createSlug(title); // "my-awesome-article-title-with-special-chars-numbers-123-eau"
How it works: This JavaScript function `createSlug` converts a given string into a URL-friendly slug. It uses a series of string methods and regular expressions to normalize characters (e.g., 'é' to 'e'), remove diacritics, convert to lowercase, trim whitespace, remove non-alphanumeric characters (except hyphens), replace spaces with single hyphens, and finally, collapse multiple hyphens into one. This is essential for creating clean, SEO-friendly URLs and file names.

Need help integrating this into your project?

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

Hire DigitalCodeLabs