If you have been coding JavaScript for some time now, you may have came across (or even used) "escape" and "unescape", which is commonly found in scripts that need to convert certain characters in the string so that it can be used in cookies, URL's etc. But there are 2 other methods that should be used instead of the old "escape", as that has been deprecated.
The two other methods are "encodeURI()" and "encodeURIComponent()". The difference betweem the two is that the "encodeURIComponent()" method encodes a lot more characters then "encodeURI()".
Which one do you use?
Well, it depends on the task you are doing. For example, if I was building a query string for the URL from user input, I would most probably use "encodeURIComponent()" because it supports a lot more characters that could end up breaking the query string.
Let me show you an example.
<script type="text/javascript">
|
|
Say that you had a page where visitors could input some information that could contain all sorts of characters. The user input information would be stored in the variable "userInputStr", then we come to the next line of code where we build the query string. We can't just add the "userInputStr" variable to the "searchStr" variable, we need to encode the user input first. To do that we use "encodeURIComponent()", because if the user input information contained characters like the ampersand "&", it would break the query string. Query strings are made up of variables, each variables value is separated with an ampersand "&" character.
Like so:
index.html?name=john&id=305
|
|
Everything to the right of the question mark is variables and values. So the variable "name" value is "john", the variable "id" value is "305". If you see, each one is separated by an ampersand character, which is a special character when used like above, this is why characters like that need to be encoded.
To decode a string is very easy, all you do is use "decodeURI()" or "decodeURIComponent()", depending on which one you use to encode with. You must decode the string using the correct method which you encoded with. So, for example, you can't encode with "encodeURI()" and then decode it with "decodeURIComponent()".
| Discuss Tutorial: Encoding and decoding URLs | 0 Comments |