Creating URL Slugs / Permalinks in C# (csharp)

Bit of a code dump but what the hey it will have to do. In wordpress we have a wonderful set of functions that takes your title and converts it to a URL friendly version in the slug ** or **permalink area.

This also handles foreign characters converting them to their standard ASCII equivalent. I generally use two string extensions in C# to perform this task; its incredibly simple and pretty darn clean (I hope). Feel free to expand or change to your requirements.

C# Slug Code or URL Cleanser or Permalink Builder

/// <summary>
/// Convert Foreign Accent Characters
/// </summary>
/// 
/// <returns>Common ASCII representation</returns>
public static string RemoveAccent(this string s)
{
    return Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(s));
}

/// <summary>
/// Cleanses String for URL
/// </summary>
/// 
/// <returns>URL Friendly String</returns>
public static string Clean(this string s)
{
    var sb = new StringBuilder(
        Regex.Replace(
            HttpUtility.HtmlDecode(s).RemoveAccent(), @"(?!W+$)W+(?<!^W+)", "").Trim()
            );
    sb.Replace(" ", "-"); 

    return sb.ToString().ToLower();
}

As all links are essentially generated in your page I use this in the page itself; obviously you could expand the scope to a custom HTML helper function or any other of the many, many, ways .net lets you abuse webpages. I left

string.RemoveAccent as a separate function, as I have “other” uses for it, though its pretty obvious how to integrate this.

Note: I’ve not attached the code to this page as the above listing is enough; hence there is also no test files to accompany it; use your imagination.
If you want have ampersands in your URL it may be worth changing this to and before the regex replace kicks in. Technically and is pretty worthless in seo but it does add to user-readability. This would look like below.

public static string Clean(this string s)
{
    var sb = new StringBuilder(
        Regex.Replace(
            HttpUtility.HtmlDecode(s.Replace("&","and"))
                                    .RemoveAccent(), @"(?!W+$)W+(?<!^W+)", "")
                                    .Trim()
            );
    sb.Replace("  ", " ").Replace(" ", "-"); 

    return sb.ToString().ToLower();
}

One thought on “Creating URL Slugs / Permalinks in C# (csharp)

Comments are closed.