How do I generate a Friendly URL in C#?

前端 未结 4 1678
生来不讨喜
生来不讨喜 2020-12-04 10:10

How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL\'s like Stack Overflow?

4条回答
  •  再見小時候
    2020-12-04 11:00

    Here's how we do it. Note that there are probably more edge conditions than you realize at first glance..

    if (String.IsNullOrEmpty(title)) return "";
    
    // remove entities
    title = Regex.Replace(title, @"&\w+;", "");
    // remove anything that is not letters, numbers, dash, or space
    title = Regex.Replace(title, @"[^A-Za-z0-9\-\s]", "");
    // remove any leading or trailing spaces left over
    title = title.Trim();
    // replace spaces with single dash
    title = Regex.Replace(title, @"\s+", "-");
    // if we end up with multiple dashes, collapse to single dash            
    title = Regex.Replace(title, @"\-{2,}", "-");
    // make it all lower case
    title = title.ToLower();
    // if it's too long, clip it
    if (title.Length > 80)
        title = title.Substring(0, 79);
    // remove trailing dash, if there is one
    if (title.EndsWith("-"))
        title = title.Substring(0, title.Length - 1);
    return title;
    

提交回复
热议问题