Skip to content

Instantly share code, notes, and snippets.

@veggerby
Created July 5, 2011 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veggerby/1064439 to your computer and use it in GitHub Desktop.
Save veggerby/1064439 to your computer and use it in GitHub Desktop.
Generate a "slug" for a URL from a string
public static string ToSlug(this string message)
{
// replace space with -
message = Regex.Replace(message, @"[\s/\\\.,+|_]+", "-");
// normalize the message
message = message.Normalize(NormalizationForm.FormD);
// do simple DK char replace
message = message.Replace("ø", "oe").Replace("Ø", "Oe").Replace("æ", "ae").Replace("Æ", "Ae").Replace("å", "aa").Replace("Å", "Aa");
var 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment