Generating a Slug From a String

.NET General, Code No Comments

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();
}

Leave a Reply

Icons by N.Design Studio. Designed By Ben Swift. Powered by WordPress, Search Optimization and Free WordPress Themes
Entries RSS Comments RSS Log in