Nikolay_Kashev

Slug Generator

Dec 5th, 2024 (edited)
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.89 KB | None | 0 0
  1. using System;
  2. using System.Text.RegularExpressions;
  3.  
  4. public class SlugGenerator
  5. {
  6.     public static string GenerateSlug(string title)
  7.     {
  8.         if (string.IsNullOrWhiteSpace(title))
  9.             return string.Empty;
  10.  
  11.         // Convert to lowercase
  12.         title = title.ToLowerInvariant();
  13.  
  14.         // Replace whitespaces with dashes
  15.         title = Regex.Replace(title, @"\s+", "-");
  16.  
  17.         // Remove invalid characters
  18.         title = Regex.Replace(title, @"[^a-z0-9\-]", "");
  19.  
  20.         // Replace multiple dashes with a single dash
  21.         title = Regex.Replace(title, @"-+", "-");
  22.  
  23.         // Trim dashes from the ends
  24.         title = title.Trim('-');
  25.  
  26.         return title;
  27.     }
  28.  
  29.     public static void Main()
  30.     {
  31.         string productTitle = Console.ReadLine();
  32.         string slug = GenerateSlug(productTitle);
  33.         Console.WriteLine($"Slug: {slug}");
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment