How does Stack Overflow generate its SEO-friendly URLs?

后端 未结 21 1851
-上瘾入骨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:00

    You can use the following helper method. It can convert the Unicode characters.

    public static string ConvertTextToSlug(string s)
    {
        StringBuilder sb = new StringBuilder();
    
        bool wasHyphen = true;
    
        foreach (char c in s)
        {
            if (char.IsLetterOrDigit(c))
            {
                sb.Append(char.ToLower(c));
                wasHyphen = false;
            }
            else
                if (char.IsWhiteSpace(c) && !wasHyphen)
                {
                    sb.Append('-');
                    wasHyphen = true;
                }
        }
    
        // Avoid trailing hyphens
        if (wasHyphen && sb.Length > 0)
            sb.Length--;
    
        return sb.ToString().Replace("--","-");
    }
    

提交回复
热议问题