SHARE
    TWEET
    giammin

    Asp.net Convert a title to a FriendlyUrl

    Jul 31st, 2014
    1,358
    0
    Never
    Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
    C# 1.72 KB | None | 0 0
    1. //http://stackoverflow.com/questions/25259/how-does-stack-overflow-generate-its-seo-friendly-urls/25063322#25063322
    2. public static string ToFriendlyUrl(string title, bool utf8 = false, int maxlen=80)
    3. {
    4. if (title == null) return "";
    5. int len = title.Length;
    6. bool prevdash = false;
    7. var sb = new StringBuilder(len);
    8. char c;
    9. for (int i = 0; i < len; i++)
    10. {
    11. c = title[i];
    12. if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
    13. {
    14. sb.Append(c);
    15. prevdash = false;
    16. }
    17. else if (c >= 'A' && c <= 'Z')
    18. {
    19. // tricky way to convert to lowercase
    20. sb.Append((char)(c | 32));
    21. prevdash = false;
    22. }
    23. else if (c == ' ' || c == ',' || c == '.' || c == '/' ||
    24. c == '\\' || c == '-' || c == '_' || c == '=')
    25. {
    26. if (!prevdash && sb.Length > 0)
    27. {
    28. sb.Append('-');
    29. prevdash = true;
    30. }
    31. }
    32. else if (c >= 128)
    33. {
    34. int prevlen = sb.Length;
    35. if (utf8)
    36. {
    37. sb.Append(HttpUtility.UrlEncode(c.ToString(CultureInfo.InvariantCulture),Encoding.UTF8));
    38. }
    39. else
    40. {
    41. //http://meta.stackexchange.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696
    42. sb.Append(RemapInternationalCharToAscii(c));
    43. }
    44. if (prevlen != sb.Length) prevdash = false;
    45. }
    46. if (i == maxlen) break;
    47. }
    48. if (prevdash)
    49. return sb.ToString().Substring(0, sb.Length - 1);
    50. else
    51. return sb.ToString();
    52. }
    Advertisement
    Add Comment
    Please, Sign In to add comment
    Public Pastes
    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
    Not a member of Pastebin yet?
    Sign Up, it unlocks many cool features!

    AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /