Introduction

Let us start up by loosening up and indulging in an inside joke...
Joke 1
"Why do Java Developers wear glasses?
Because they can't see-sharp."
I could not resist but to manufacture a relevant comeback for the above.
Joke 2
"Why do C# Developers love coffee?
Because Java is best served in a cup."
Alright, enough with the humor. Let us get right into it.
Below is a universal algorithm that produces slugs by following the steps below.
  • Removing all accents (e.g s => s etc...);
  • Making the slug lower case;
  • Removing all special characters;
  • Removing all additional spaces in favor of just one;
  • and Replacing all the spaces with a hyphen"-"
Here's the solution below,
  1. using System.Globalization;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. namespace ProjectTitle.Extensions
  6. {
  7. /// <summary>
  8. /// Contains all custom written string related Extension Methods.
  9. /// </summary>
  10. public static class StringExtensions
  11. {
  12. /// <summary>
  13. /// Removes all accents from the input string.
  14. /// </summary>
  15. /// <param name="text">The input string.</param>
  16. /// <returns></returns>
  17. public static string RemoveAccents(this string text)
  18. {
  19. if (string.IsNullOrWhiteSpace(text))
  20. return text;
  21. text = text.Normalize(NormalizationForm.FormD);
  22. char[] chars = text
  23. .Where(c => CharUnicodeInfo.GetUnicodeCategory(c)
  24. != UnicodeCategory.NonSpacingMark).ToArray();
  25. return new string(chars).Normalize(NormalizationForm.FormC);
  26. }
  27. /// <summary>
  28. /// Turn a string into a slug by removing all accents,
  29. /// special characters, additional spaces, substituting
  30. /// spaces with hyphens & making it lower-case.
  31. /// </summary>
  32. /// <param name="phrase">The string to turn into a slug.</param>
  33. /// <returns></returns>
  34. public static string Slugify(this string phrase)
  35. {
  36. // Remove all accents and make the string lower case.
  37. string output = phrase.RemoveAccents().ToLower();
  38. // Remove all special characters from the string.
  39. output = Regex.Replace(output, @"[^A-Za-z0-9\s-]", "");
  40. // Remove all additional spaces in favour of just one.
  41. output = Regex.Replace(output, @"\s+", " ").Trim();
  42. // Replace all spaces with the hyphen.
  43. output = Regex.Replace(output, @"\s", "-");
  44. // Return the slug.
  45. return output;
  46. }
  47. }
  48. }

Conclusion

There you have it, a Slugify algorithm that takes care of whatever end-users will be throwing at it.
Please provide feedback below in the comments, critique wherever possible and I hope this solution helps everyone in the long run.