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)
{
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 ));
// output:
// 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