Thoughts on Technology, Methodology and Programming.

How to get rid of an ampersand in the query string

Posted by Marcus Wyatt on 10 April 2007

If you’ve worked on web applications, you probably know that using the query string to pass data is important. But how would you handle a string that contains an ampersand in the query string. Here is an example:

string title = “Jack & Jill”;

string category = “Nursery Rhyme”;

Response.Redirect(“Books.aspx?title=” + title + “&category=” + category);

If you try to run the code example above the title query parameter will only contain ‘Jack’. This is a problem, so how do you escape the ampersand in the title variable. You could use the escape function in Javascript.

window.escape("Jack & Jill");

Another option is to use the HttpUtility.UrlEncode method:

string title = HttpUtility.UrlEncode(“Jack & Jill”, Encoding.ASCII);

string category = “Nursery Rhyme”;

Response.Redirect(“loadNurseryRhyme?title=” + title + “&category=” + category);

The string ‘Jack & Jill’ is now escaped as follows ‘Jack+%26+Jill’ and you don’t lose any information in your query string.


Technorati Tags:

Powered by ScribeFire.


3 Responses to “How to get rid of an ampersand in the query string”

  1. Rob said


    I just found your NSpecify framework and really like it. But, when I installed the release of NUnit 2.4 it didn’t seem to work any more (it previously worked with Beta 1 of 2.4). I was wondering if you could do a build against the new NUnit bits and release a new version of NSpecify. I would really love to work with it, but I cannot make any progress at present.

    Thanks in advance!

  2. […] Original source: https://exceptionz.wordpress.com/2007/04/10/how-to-get-rid-of-an-ampersand-in-the-query-string/ […]

  3. […] Original source: https://exceptionz.wordpress.com/2007/04/10/how-to-get-rid-of-an-ampersand-in-the-query-string/ […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: