Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to decode an encoded string in JavaScript?
In JavaScript, string decoding refers to converting encoded strings back to their original form. While escape() and unescape() were historically used, modern JavaScript provides better alternatives like decodeURIComponent() and decodeURI().
Using unescape() (Deprecated)
The unescape() method decodes strings encoded by the escape() method. It replaces hexadecimal escape sequences with their corresponding characters.
Syntax
unescape(string)
Example
<html>
<body>
<script type="text/javascript">
// Special character encoded with escape function
var str = escape("Tutorialspoint!!");
document.write("Encoded : " + str);
document.write("<br>");
// unescape() function
document.write("Decoded : " + unescape(str));
</script>
</body>
</html>
Output
Encoded : Tutorialspoint%21%21 Decoded : Tutorialspoint!!
Characters Not Encoded
The escape() method does not encode certain characters like @ and . (dot):
<html>
<body>
<script type="text/javascript">
str = escape("My gmail address is robbinhood@rocketmail.com");
document.write("Encoded : " + str);
document.write("<br>");
// unescape() function
document.write("Decoded : " + unescape(str));
</script>
</body>
</html>
Output
Encoded : My%20gmail%20address%20is%20robbinhood@rocketmail.com Decoded : My gmail address is robbinhood@rocketmail.com
Modern Alternatives (Recommended)
Since escape() and unescape() are deprecated, use these modern methods:
Using decodeURIComponent()
<html>
<body>
<script type="text/javascript">
var encoded = "Hello%20World%21";
var decoded = decodeURIComponent(encoded);
document.write("Encoded: " + encoded);
document.write("<br>");
document.write("Decoded: " + decoded);
</script>
</body>
</html>
Output
Encoded: Hello%20World%21 Decoded: Hello World!
Comparison
| Method | Status | Use Case |
|---|---|---|
unescape() |
Deprecated | Legacy code only |
decodeURIComponent() |
Modern | URL components |
decodeURI() |
Modern | Complete URIs |
Conclusion
While unescape() can decode escaped strings, use decodeURIComponent() or decodeURI() for modern JavaScript applications as they provide better UTF-8 support and follow current standards.
