SHARE
TWEET

Asp.net Convert a title to a FriendlyUrl

giammin Jul 31st, 2014 413 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //http://stackoverflow.com/questions/25259/how-does-stack-overflow-generate-its-seo-friendly-urls/25063322#25063322
  2.  
  3. public static string ToFriendlyUrl(string title, bool utf8 = false, int maxlen=80)
  4. {
  5.     if (title == null) return "";
  6.  
  7.     int len = title.Length;
  8.     bool prevdash = false;
  9.     var sb = new StringBuilder(len);
  10.     char c;
  11.  
  12.     for (int i = 0; i < len; i++)
  13.     {
  14.         c = title[i];
  15.         if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
  16.         {
  17.             sb.Append(c);
  18.             prevdash = false;
  19.         }
  20.         else if (c >= 'A' && c <= 'Z')
  21.         {
  22.             // tricky way to convert to lowercase
  23.             sb.Append((char)(c | 32));
  24.             prevdash = false;
  25.         }
  26.         else if (c == ' ' || c == ',' || c == '.' || c == '/' ||
  27.             c == '\\' || c == '-' || c == '_' || c == '=')
  28.         {
  29.             if (!prevdash && sb.Length > 0)
  30.             {
  31.                 sb.Append('-');
  32.                 prevdash = true;
  33.             }
  34.         }
  35.         else if (c >= 128)
  36.         {
  37.             int prevlen = sb.Length;
  38.             if (utf8)
  39.             {
  40.                 sb.Append(HttpUtility.UrlEncode(c.ToString(CultureInfo.InvariantCulture),Encoding.UTF8));
  41.             }
  42.             else
  43.             {
  44.                 //http://meta.stackexchange.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696
  45.                 sb.Append(RemapInternationalCharToAscii(c));
  46.             }
  47.                    
  48.             if (prevlen != sb.Length) prevdash = false;
  49.         }
  50.         if (i == maxlen) break;
  51.     }
  52.  
  53.     if (prevdash)
  54.         return sb.ToString().Substring(0, sb.Length - 1);
  55.     else
  56.         return sb.ToString();
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top