Generating a Slug From a String

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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.