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,
- using System.Globalization;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- namespace ProjectTitle.Extensions
- {
- /// <summary>
- /// Contains all custom written string related Extension Methods.
- /// </summary>
- public static class StringExtensions
- {
- /// <summary>
- /// Removes all accents from the input string.
- /// </summary>
- /// <param name="text">The input string.</param>
- /// <returns></returns>
- public static string RemoveAccents(this string text)
- {
- if (string.IsNullOrWhiteSpace(text))
- return text;
- text = text.Normalize(NormalizationForm.FormD);
- char[] chars = text
- .Where(c => CharUnicodeInfo.GetUnicodeCategory(c)
- != UnicodeCategory.NonSpacingMark).ToArray();
- return new string(chars).Normalize(NormalizationForm.FormC);
- }
- /// <summary>
- /// Turn a string into a slug by removing all accents,
- /// special characters, additional spaces, substituting
- /// spaces with hyphens & making it lower-case.
- /// </summary>
- /// <param name="phrase">The string to turn into a slug.</param>
- /// <returns></returns>
- public static string Slugify(this string phrase)
- {
- // Remove all accents and make the string lower case.
- string output = phrase.RemoveAccents().ToLower();
- // Remove all special characters from the string.
- output = Regex.Replace(output, @"[^A-Za-z0-9\s-]", "");
- // Remove all additional spaces in favour of just one.
- output = Regex.Replace(output, @"\s+", " ").Trim();
- // Replace all spaces with the hyphen.
- output = Regex.Replace(output, @"\s", "-");
- // Return the slug.
- return output;
- }
- }
- }
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.

quan buiPosted Apr 16, 2021, 7:52 AM
Nice, thank you.
Former memberPosted Oct 30, 2019, 6:30 AM
i shall be thankful to you plz sir contact me on whatsap+ 92308_8857365
Former memberPosted Oct 30, 2019, 6:29 AM
hi can you contact me on whatsap plz sir i shall b th
Sourav Kumar DasPosted Oct 29, 2019, 11:47 PM
Nice Article.