Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently remove a query string by Key from a Url?

How to remove a query string by Key from a Url?

I have the below method which works fine but just wondering is there any better/shorter way? or a built-in .NET method which can do it more efficiently?

 public static string RemoveQueryStringByKey(string url, string key)         {             var indexOfQuestionMark = url.IndexOf("?");             if (indexOfQuestionMark == -1)             {                 return url;             }              var result = url.Substring(0, indexOfQuestionMark);             var queryStrings = url.Substring(indexOfQuestionMark + 1);             var queryStringParts = queryStrings.Split(new [] {'&'});             var isFirstAdded = false;              for (int index = 0; index <queryStringParts.Length; index++)             {                 var keyValue = queryStringParts[index].Split(new char[] { '=' });                 if (keyValue[0] == key)                 {                     continue;                 }                  if (!isFirstAdded)                 {                     result += "?";                     isFirstAdded = true;                 }                 else                 {                     result += "&";                 }                  result += queryStringParts[index];             }              return result;         } 

For example I can call it like:

  Console.WriteLine(RemoveQueryStringByKey(@"http://www.domain.com/uk_pa/PostDetail.aspx?hello=hi&xpid=4578", "xpid")); 

Hope the question is clear.

Thanks,

like image 272
The Light Avatar asked Jun 15 '12 14:06

The Light


People also ask

How do you separate a query string from a URL?

The query string is composed of a series of field-value pairs. Within each pair, the field name and value are separated by an equals sign, " = ". The series of pairs is separated by the ampersand, " & " (or semicolon, " ; " for URLs embedded in HTML and not generated by a <form>...

How do I get rid of query string?

To remove a querystring from a url, use the split() method to split the string on a question mark and access the array element at index 0 , e.g. url. split('? ')[0] . The split method will return an array containing 2 substrings, where the first element is the url before the querystring.

How do I remove values from a URL?

Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you. To use it, simply do something like this: var originalURL = "http://yourewebsite.com?id=10&color_id=1"; var alteredURL = removeParam("color_id", originalURL);

How do I separate multiple query parameters in URL?

URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).


2 Answers

This works well:

public static string RemoveQueryStringByKey(string url, string key) {                        var uri = new Uri(url);      // this gets all the query string key value pairs as a collection     var newQueryString = HttpUtility.ParseQueryString(uri.Query);      // this removes the key if exists     newQueryString.Remove(key);      // this gets the page path from root without QueryString     string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);      return newQueryString.Count > 0         ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)         : pagePathWithoutQueryString; } 

an example:

RemoveQueryStringByKey("https://www.google.co.uk/search?#hl=en&output=search&sclient=psy-ab&q=cookie", "q"); 

and returns:

https://www.google.co.uk/search?#hl=en&output=search&sclient=psy-ab 
like image 155
The Light Avatar answered Sep 29 '22 03:09

The Light


    var queryString = "hello=hi&xpid=4578";     var qs = System.Web.HttpUtility.ParseQueryString(queryString);     qs.Remove("xpid");     var newQuerystring = qs.ToString(); 

This still works in .NET 5.

like image 38
C.M. Avatar answered Sep 29 '22 03:09

C.M.