Computer >> Computer tutorials >  >> Programming >> Javascript

How to decode an encoded string in JavaScript?


Decoding

In JavaScript, to decode a string unescape() method is used. This method takes a string, which is encoded by escape() method, and decodes it. The hexadecimal characters in a string will be replaced by the actual characters they represent using unescape() method.

Syntax

unescape(string)

Example

In the following the two exclamation marks have converted to hexadecimal characters using escape() method. Later on those marks were decoded in to their natural characters using unescape() method. 

<html>
<body>
<script type="text/javascript">
   // Special character encoded with escape function
   var str = escape("Tutorialspoint!!");
   document.write("</br>");
   document.write("Encoded : " + str);
   // unescape() function
   document.write("Decoded : " + unescape(str))
</script>
</body>
</html>

Output

Encoded : Tutorialspoint%21%21
Decoded : Tutorialspoint!!


There is an exception that the characters .(dot) and @ wont convert in to hexadecimal characters. For instance, in the following code when escape() method is used all the characters have converted to hexadecimal except .(dot) and @.

Example

<html>
<body>
<script type="text/javascript">
   str = escape("My gmail address is [email protected]")
   document.write("Encoded : " + str);
   document.write("</br>");
   // unescape() function
   document.write("Decoded : " + unescape(str))
</script>
</body>
</html>

Output

Encoded : My%20gmail%20address%20is%[email protected]
Decoded : My gmail address is [email protected]