Generating a Slug From a String
Posted: October 2, 2009 Filed under: .NET General, Code | Tags: Extension Methods, Slug, Unicode, url Leave a comment »I can’t (and won’t) take full credit for this extension method. The hardcore Unicode stuff is from Michael Kaplan’s blog (jeez, he is hardcore). There is a little danish “stuff” included, for special characters æ, ø and å, which can also be written “ae”, “oe” an “aa”.
public static string ToSlug(this string message)
{
// replace space with -
message = Regex.Replace(message, @"[\s/\\\.,+|_]+", "-");
// normalize the message
message = message.Normalize(NormalizationForm.FormD);
message = message.Replace("ø", "oe").Replace("Ø", "Oe").Replace("æ", "ae").Replace("Æ", "Ae").Replace("å", "aa").Replace("Å", "Aa");
StringBuilder result = new StringBuilder();
for (int i = 0; i < message.Length; i++)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(message[i]);
if (uc != UnicodeCategory.NonSpacingMark)
{
result.Append(message[i]);
}
}
return Regex.Replace(result.ToString().Normalize(NormalizationForm.FormC), @"[^a-zA-Z0-9\-]", "").ToLower();
}