JAVASCRIPT

Sanitize a String for Use as a URL Slug

Transform any string into a clean, SEO-friendly URL slug by converting to lowercase, replacing special characters with hyphens, and trimming excess.

function createUrlSlug(text) {
  return text
    .toString()
    .normalize('NFD').replace(/[\u0300-\u036f]/g, '') // Remove diacritics
    .toLowerCase() // Convert to lowercase
    .trim() // Trim leading/trailing whitespace
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/[^\w-]+/g, '') // Remove all non-word chars (except hyphens)
    .replace(/--+/g, '-') // Replace multiple hyphens with single
    .replace(/^-+/, '') // Remove leading hyphens
    .replace(/-+$/, ''); // Remove trailing hyphens
}

// Example usage:
// console.log(createUrlSlug("My Awesome Post Title!")); // "my-awesome-post-title"
// console.log(createUrlSlug("  Article with Spécial Chars & Numbers 123  ")); // "article-with-special-chars-numbers-123"
// console.log(createUrlSlug("Another post---title--")); // "another-post-title"
How it works: This JavaScript function transforms a given string into a URL-friendly slug. It performs several operations: removes diacritics, converts to lowercase, trims whitespace, replaces spaces with single hyphens, removes any remaining non-word characters (except hyphens), and cleans up redundant or leading/trailing hyphens using a series of regular expressions and string methods to create a clean slug.

Need help integrating this into your project?

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

Hire DigitalCodeLabs