Developer Blog
Articles about Using Microsoft Developer Tools

Abbreviating URLs

Thursday, April 29, 2010 7:35 AM by jonwood

NOTE: This article has been updated and moved to: Abbreviating URLs.

Recently, I had a case where an ASP.NET page displayed the user's URL in a side column. This worked fine except that I found some users had very long URLs, which didn't look right.

It occurred to me that I could simple truncate the visible URL while still keeping the underlying link the same. However, when I truncated the URL by trimming excess characters, I realized it could be done more intelligently.

For example, consider the URL If I wanted to keep it within 40 characters, I could trim it to The problem is that this abbreviation could be more informative. For example, is it a directory or a page? And, if it's a page, what kind? And what exactly does the "u" at the end stand for?

Wouldn't it be a little better if I instead abbreviated this URL to We've lost a few characters due to the three dots that show information is missing. But we can still see the domain, and the page name and type.

The code is Listing 1 abbreviates a URL is this way. The UrlHelper class contains just a single, static method, LimitLength(). This method takes a URL string and a maximum length arguments, and attempts to abbreviate the URL so that it will fit within the specified number of characters as described above.

public class UrlHelper
  /// <summary>
  /// made to shorten less than 5 characters.
  /// </summary>
  /// <returns></returns>
  public static string LimitLength(string url, int maxLength)
    if (maxLength < 5)
      maxLength = 5;
    if (url.Length > maxLength)
      // Remove protocol
        url = url.Remove(0, i + 1);
      // Remove leading delimiters
      i = 0;
      if (i > 0)
        url = url.Remove(0, i);
      // Remove trailing delimiter
        url = url.Remove(url.Length - 1);
      if (url.Length > maxLength)
        i = url.IndexOfAny(Delimiters);
        if (i >= 0)
          string first = url.Substring(0, i + 1);
          string last = url.Substring(i);
          bool trimmed = false;
            i = last.IndexOfAny(Delimiters, 1);
            last = last.Substring(i);
            trimmed = true;
          if (trimmed)
    return url;

Listing 1: UrlHelper class.



Categories:   C# .NET | ASP.NET