This article will describe the escape and unescape functions in JavaScript.
What are escape String Functions in JavaScript?
The “escape()” function encodes the string to make it accessible for network transmission. It encodes all the non-ASCII characters to their two or four-digit hexadecimal numbers. Moreover, a blank space is converted to “%20” by the escape function.
Syntax
Follow the given syntax to use the escape() method:
Here, “string” is the parameter passed in a method for encoding.
Example
First, create a string named “str”:
Print the string on the page using the “document.write()” method:
Call the escape() method by passing a string as an argument and store the resultant encoded string in a variable “encodeStr”:
Finally, print the encoded string on the page:
The output shows the original and encoded strings. Here, you can see that the “spaces” converted to “%20”, “(“ to “%28”, “!” to “%21” and “)” to “%29”:
What are unescape String Functions in JavaScript?
The unescape() method decodes the string in its original state. It converts all the hexadecimal values to the relevant character that they represent. Some browsers do not support this method, so for that, you can utilize the “ decodeURIComponent()” or “decodeURI()” as a replacement.
Syntax
Use the below-mentioned syntax for decoding the encoded string using unescape() method:
It takes an encoded string as a parameter.
Example
Here, call the unescape() method by passing an encoded string “encodeStr” as an argument:
Print the decoded string on the page:
The output displays original, encoded, and decoded strings:
That’s all about escape and unescape functions in JavaScript.
Conclusion
The escape and unescape functions are used for encoding and decoding the strings to make a string accessible for transmission over a network. The escape() method converts all the non-ASCII values to their hexadecimal numbers, and the unescape() method will convert the encoded string into its original string by converting hexadecimal values to their non-ASCII characters. In this article, we described the escape and unescape functions in JavaScript.