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
- {
-
-
-
- public static class StringExtensions
- {
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
- public static string Slugify(this string phrase)
- {
-
- string output = phrase.RemoveAccents().ToLower();
-
-
- output = Regex.Replace(output, @"[^A-Za-z0-9\s-]", "");
-
-
- output = Regex.Replace(output, @"\s+", " ").Trim();
-
-
- output = Regex.Replace(output, @"\s", "-");
-
-
- 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.