42

URL http://localhost/mysite/mypage?param=123 works fine. However, if I want to put some special characters in param, like ?, /, \, then the URL becomes http://localhost/mysite/mypage?param=a=?&b=/ or http://localhost/mysite/mypage?param=http://www.example.com/page2?a=\&b=... which won't work. How do I resolve this issue?

Belisarius
  • 21
  • 1
  • 1
  • 7
KentZhou
  • 24,805
  • 41
  • 134
  • 200

7 Answers7

37

You have to encode special characters in URLs. See: http://www.w3schools.com/tags/ref_urlencode.asp

Steven P.
  • 941
  • 5
  • 15
  • 1
    If you have special characters like " / ? : @ & = + $ #" then you need to use this extended function: https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp – pegaltier Jul 31 '19 at 09:16
  • 2
    The more valid reference would be MDN, see below... https://stackoverflow.com/a/35377890/147618 – Dharmang Dec 23 '19 at 10:48
18

You need to encode the query parameters before combining them to form a url. The function needed here is encodeURIComponent.For example,

the url you need to create is:

http://localhost/mysite/mypage?param=a=?&b=/

Now, assuming that ? and / comes as variables, you need to encode them before putting in the url. So lets create your url using this function(I am expecting two query parameters):

 var q1 = "a=?"; //came from some input or something
    var q2 = "/"; //came from somewhere else

    var faultyUrl =  "http://localhost/mysite/mypage?param="+ q1 +"&b=" + q2; 
// "http://localhost/mysite/mypage?param=a=?&b=/"


    var properUrl =  "http://localhost/mysite/mypage?param="+ encodeURIComponent(q1) +"&b=" + encodeURIComponent(q2); 
//"http://localhost/mysite/mypage?param=a%3D%3F&b=%2F"

This function is in basic JS and supported in all the browsers.

Kop4lyf
  • 4,520
  • 1
  • 25
  • 31
8

Easy way to pass QueryString value with special character using javascript:

var newURL=encodeURIComponent(uri);
window.location="/abc/abc?q="+newURL;
Hardik Mandankaa
  • 3,129
  • 4
  • 23
  • 32
5

In JavaScript you can use the encodeURI() function.

ASP has the Server.URLEncode() function.

You can use HttpServerUtility.UrlEncode in .NET.

Belisarius
  • 21
  • 1
  • 1
  • 7
Vishal Seth
  • 4,948
  • 7
  • 26
  • 28
  • in .Net you want to use `HttpUtility.UrlEncode` https://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode(v=vs.110).aspx – GJKH Mar 07 '16 at 13:27
2

You need to use encode special characters, see this page for a reference.

If you're using PHP, there's a function to do this, called urlencode().

JYelton
  • 35,664
  • 27
  • 132
  • 191
2

I did below, it works fine.

const myQueryParamValue = "You&Me";
const ajaxUrl = "www.example.com/api?searchText="+encodeURIComponent(myQueryParamValue)
Thavaprakash Swaminathan
  • 6,226
  • 2
  • 30
  • 31
0

You need to substitute the characters with URL entities. Some information here.

Moonshield
  • 925
  • 9
  • 16