Sometimes we need to operate on the query parameters in a URL address. In order not to break the original structure of the URL, we generally cannot directly add & query = value after the URL, this is especially troublesome when there are multiple parameters in our URL.
The following two small methods are specifically used to add a query parameter to a URL or delete a query parameter. These two methods hide whether the original URL has any parameters, are there any fragment (# anchor) details and processing?
/** // <Summary>
/// Add a query to an URL.
/// If the URL has not any query, then append the query key and value to it.
/// If the URL has some queries, then check it if exists the query key already, replace the value, or append the key and value
/// If the URL has any fragment, append fragments to the URL end.
/// </Summary>
Public static string SafeAddQueryToURL (string key, string value, string url)
{
Int fragPos = url. LastIndexOf ("#");
String fragment = string. Empty;
If (fragPos>-1)
{
Fragment = url. Substring (fragPos );
Url = url. Substring (0, fragPos );
}
Int querystart = url. IndexOf ("? ");
If (querystart <0)
{
Url + = "? "+ Key +" = "+ value;
}
Else
{
Regex reg = new Regex (@"(? <= [& \?]) "+ Key + @" = [^ \ s & #] * ", RegexOptions. Compiled );
If (reg. IsMatch (url ))
Url = reg. Replace (url, key + "=" + value );
Else
Url + = "&" + key + "=" + value;
}
Return url + fragment;
}
/** // <Summary>
/// Remove a query from url
/// </Summary>
/// <Param name = "key"> </param>
/// <Param name = "url"> </param>
/// <Returns> </returns>
Public static string SafeRemoveQueryFromURL (string key, string url)
{
Regex reg = new Regex (@ "[& \?] "+ Key + @" = [^ \ s & #] * &? ", RegexOptions. Compiled );
Return reg. Replace (url, new MatchEvaluator (PutAwayGarbageFromURL ));
}
Private static string PutAwayGarbageFromURL (Match match)
{
String value = match. Value;
If (value. EndsWith ("&"))
Return value. Substring (0, 1 );
Else
Return string. Empty;
}
Test:
String s = "http://www.cnblogs.com /? A = 1 & B = 2 & c = 3 # tag ";
WL (SafeRemoveQueryFromURL ("a", s ));
WL (SafeRemoveQueryFromURL ("B", s ));
WL (SafeRemoveQueryFromURL ("c", s ));
WL (SafeAddQueryToURL ("d", "new", s ));
WL (SafeAddQueryToURL ("a", "newvalue", s ));
// The output is as follows:
// Http://www.cnblogs.com /? B = 2 & c = 3 # tag
// Http://www.cnblogs.com /? A = 1 & c = 3 # tag
// Http://www.cnblogs.com /? A = 1 & B = 2 # tag
// Http://www.cnblogs.com /? A = 1 & B = 2 & c = 3 & d = new # tag
// Http://www.cnblogs.com /? A = newvalue & B = 2 & c = 3 # tag