How does Stack Overflow generate its SEO-friendly URLs?

后端 未结 21 2304
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:27

What is a good complete regular expression or some other process that would take the title:

How do you change a title to be part of the URL like Stack

21条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 05:02

    The stackoverflow solution is great, but modern browser (excluding IE, as usual) now handle nicely utf8 encoding:

    enter image description here

    So I upgraded the proposed solution:

    public static string ToFriendlyUrl(string title, bool useUTF8Encoding = false)
    {
        ...
    
            else if (c >= 128)
            {
                int prevlen = sb.Length;
                if (useUTF8Encoding )
                {
                    sb.Append(HttpUtility.UrlEncode(c.ToString(CultureInfo.InvariantCulture),Encoding.UTF8));
                }
                else
                {
                    sb.Append(RemapInternationalCharToAscii(c));
                }
        ...
    }
    

    Full Code on Pastebin

    Edit: Here's the code for RemapInternationalCharToAscii method (that's missing in the pastebin).

提交回复
热议问题