JavaScript
javascript string utility

slugify

Convert strings to URL-friendly slugs with support for multiple languages.

export function slugify(str: string): string {
  return str
    .toString()
    .toLowerCase()
    .trim()
    // Replace spaces and underscores with hyphens
    .replace(/[\s_]+/g, '-')
    // Remove special characters except hyphens
    .replace(/[^\w\-]+/g, '')
    // Replace multiple hyphens with single hyphen
    .replace(/\-\-+/g, '-')
    // Remove leading/trailing hyphens
    .replace(/^-+/, '')
    .replace(/-+$/, '');
}

Usage

slugify('Hello World!'); // "hello-world"
slugify('React & TypeScript'); // "react-typescript"
slugify('  Multiple   Spaces  '); // "multiple-spaces"
slugify('WordPress Development'); // "wordpress-development"

Advanced Version (with Unicode support)

export function slugify(str: string): string {
  return str
    .toString()
    .normalize('NFD') // Normalize unicode characters
    .replace(/[\u0300-\u036f]/g, '') // Remove diacritics
    .toLowerCase()
    .trim()
    .replace(/[\s_]+/g, '-')
    .replace(/[^\w\-]+/g, '')
    .replace(/\-\-+/g, '-')
    .replace(/^-+/, '')
    .replace(/-+$/, '');
}