Telerik blogs

In order for a string to be read from all computers sometimes it is useful to encode and decode it. This can be easily achieved using the JavaScript built-in escape() and unescape() methods. Both the escape() and the unescape() methods have the same argument – the string which will be escaped or unescaped.

The escape() method returns a string value (in Unicode format) that represents the encoded contents of the function argument. All spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character.

For example, a space is returned as "%20".

Additionally, having a code segment like:

document.write(escape("Test \n escapeText \b"));

would yield a result like the following:

Test%20%0A% escapeText %20%08

As shown, the spaces are represented by "%20", whereas the newline and backspace are represented by “%0A” and “%08”.All other characters, which bear no special meaning, are left intact.

The escape() function will encode special characters with the exception of the following:

* @ - _ + . /

The unescape() method returns a string value that represents the argument passed to the function, converted to normal characters. All characters encoded with the %xx hexadecimal form are replaced by their ASCII character set equivalents.

The escape() and unescape() functions should not be used to encode or decode URIs.

If one needs to encode/encode URIs, the encodeURI() and decodeURI() methods should be used. These two last methods encode all but the following characters:

: / ; ?

If the necessity to encode all characters arises, one can take advantage of the encodeURIComponent() method. Because the encodeURIComponent() method encodes all characters, it should be used carefully. For example, if the string represents a path such as /baseFolder/folder1/default.html, the slash characters will be encoded and will not be valid if sent as a request to a web server.

More information on the use of encodeURI(), decodeURI() and encodeURIComponent() methods is available in the following blog post.

About the Author

Yavor Angelov

Software Developer


Comments are disabled in preview mode.