1

How do I remove string in bold within following url where q= is fixed parameter?

http://abc.com/qwe.aspx?q=DIEYeGJgNwvPSJ32ic1sY5x1ZYjOZTQZD9mjWl2EQJ8=&u=/foo/boo/kb

Thanks.

Ricky
  • 34,377
  • 39
  • 91
  • 131

5 Answers5

10

it is pretty simple. I use System.Uri class to parse the url, then remove the q query string parameter, and then build a new url without this parameter:

var url = new Uri("http://abc.com/qwe.aspx?q=DIEYeGJgNwvPSJ32ic1sY5x1ZYjOZTQZD9mjWl2EQJ8=&u=/foo/boo/kb");
var query = HttpUtility.ParseQueryString(url.Query);
query.Remove("q");
UriBuilder ub = new UriBuilder(url);
ub.Query = query.ToString();
var result = ub.Uri.ToString();

Now result holds value: http://abc.com/qwe.aspx?u=/foo/boo/kb.

Oleks
  • 31,955
  • 11
  • 77
  • 132
  • 1
    This sould be the safest way to remove the query parameter. – Zebi Apr 15 '11 at 13:15
  • Too much code to do a simple thing. If the point is that url is the one found in HttpRequest, then, this could be an overkill. I'll vote for regex solution. – Matías Fidemraizer Apr 15 '11 at 13:18
  • 1
    The regex solution mentioned below as it is written at the moment does not just match the parameter named **q** but instead all parameters that end with **q** and thus won't work as intended. – Marius Schulz Apr 15 '11 at 13:22
  • 2
    Not the simplest solution, but given the lack of context for the source of the URL, it is definitely the most correct. +1 – Harry Steinhilber Apr 15 '11 at 13:30
1

input = Regex.Replace(input, "q=[^&]+", "") would be one way to do it.

John M Gant
  • 18,970
  • 18
  • 64
  • 82
0

Are the positions fixed? You can do one IndexOf("q=") and IndexOf("u=") and use SubString twice to remove the part. An other way would be to use regular expressions.

Zebi
  • 8,682
  • 1
  • 36
  • 42
0

Maybe this URL comes from some request, meaning you've that query string in the HttpRequest instance, associated to HttpContext.

In this case, you can always remove "q" query string parameter just by calling HttpContext.Current.Request.QueryString.Remove("q");

Another solution would be the one suggested by Alex.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
-1

if Q is a fixed parameter....

str = str.Replace("q=DIEYeGJgNwvPSJ32ic1sY5x1ZYjOZTQZD9mjWl2EQJ8=", "");

Otherwise I would do:

var qa = Request.QueryString;
qa.Remove("q");
var queryString = qa.ToString();
tster
  • 17,883
  • 5
  • 53
  • 72