开发者

Fastest Way to Clean a String to be used in a URL C# asp.net

开发者 https://www.devze.com 2023-01-02 20:25 出处:网络
I\'ve been using this class for a while now to cleans data into such a form that I can use it in my URL\'s and I was wondering if there\'s a faster/better way?

I've been using this class for a while now to cleans data into such a form that I can use it in my URL's and I was wondering if there's a faster/better way?

The order of the replacements is important as it ensures that theres no slashes at the beginning on completion and theres no double slashes in side of the text.

/// <summary>
/// Cleanses String for URL
/// </summary>
/// <param name="s">string</param>
/// <returns>URL Friendly String</returns>
public static string Clean(this string s)
{
    var sb = new StringBuilder(s.Trim());
    sb.Replace("&rsquo;", "");
    sb.Replace("-", " ");
    sb.Replace("/", "");
    sb.Replace("&", "and");
    sb.Replace(",", "");
    sb.Replace("  ", " ");
    sb.Replace(" ", "-");
    sb.Repl开发者_运维百科ace("'", "");
    sb.Replace(".", "");
    sb.Replace("eacute;", "e");
    sb.Replace("--", "-");

    if (sb[0].ToString() == "-") { sb[0].ToString().Replace("-", ""); }

    return sb.ToString().ToLower();
}

Thanks.


It might not look pretty, but I think what you've got here is fine in terms of readability. One alternative would be to break this down into a few Regex replace statements, but then as always with regular expressions, the readability goes out the window.

Another alternative would be to build a list of the matches and their replacements, but I think this is going to end up making the code longer in the end.

0

精彩评论

暂无评论...
验证码 换一张
取 消