There are some cases we need to pass information via URL in form of query string, parameters…In those cases, we need to make sure the query string or parameters should be consisted of allowed characters such as:
– Letters (A–Z and a–z)
– Numbers (0–9)
– Characters ‘.’,’-‘,’~’ and ‘_’
Any other characters should be encoded so that they don’t cause problems.
I myself just got problem when passed C# as value of a parameter in the query string. Here was my URL:
1 |
http://localhost:8080/reference/getSkillInfo?skillName = C# |
In below URL, # is a special character which is not only used to specify the end of query string (start of the query string is “?”) but also further specify a subsection (or fragment) of a document. And the result was the skillName that I received in the server side is just “C” not “C#” as expected.
To deal with this case, we have to encode the URL somehow. In my case, I made request to server by using Ajax. Therefore, the query string was encoded by Javascript as below:
1 2 3 4 5 6 7 8 9 10 11 12 |
function getSkillInfo(skillName) { var url = '/reference/getSkillInfo?skillName=' + encodeURIComponent(skillName); $.get(url, function (data) { //dosth }); } function getCSharpInfo() { getSkillInfo("C#"); } |
Below is some best practice when encode query string sent to sever by Javascript:
encodeURI and encodeURIComponent
escape()
Don’t use it, as it has been deprecated since ECMAScript v3.
encodeURI()
This function is used to encode a URI and encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters)
For example:
1 |
encodeURI("http://www.google.com/results with spaces") |
The ouput will be:
1 |
http://www.google.com/results%20with%20spaces |
encodeURIComponent()
We should call this method if we’re encoding a string to put in a URL component (a query string parameter)
This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #
For example:
1 |
var url = '/reference/getSkillInfo?skillName=' + encodeURIComponent("C#"); |
The output will be:
1 |
/reference/getSkillInfo?skillName=C%23 |
In Java we can encode the URI by using the method:encode of the class URLEncode. For example:
1 |
String url = "/reference/getSkillInfo?skillName=" + URLEncoder.encode("C#", "UTF-8"); |
The output will be:
1 |
/reference/getSkillInfo?skillName=C%23 |
P/S: Here is the HTML URL Encoding Reference