XhCode Online Converter Tools

Javascript Escape Unescape



Done Code:
Javascript Escape Unescape

In JavaScript, escape() and unescape() are built-in functions used to encode and decode strings, respectively. However, they are considered obsolete and should be avoided in favor of more modern functions like encodeURIComponent() and decodeURIComponent(). Here's what each does:

1. escape()
Purpose: It encodes a string by escaping non-ASCII characters and special characters that have specific meanings in URLs, like spaces, punctuation, etc.
Usage: It returns a new string where special characters are replaced by their escape sequences.
Example:
javascript

var encoded = escape("Hello, world!");
console.log(encoded); // Output: "Hello%2C%20world%21"
2. unescape()
Purpose: It decodes a string that was encoded with escape(), converting escape sequences back to their original characters.
Usage: It takes an encoded string and returns the decoded version.
Example:
javascript

var decoded = unescape("Hello%2C%20world%21");
console.log(decoded); // Output: "Hello, world!"
Modern Alternative
As mentioned, these functions are outdated. It's better to use encodeURIComponent() for encoding and decodeURIComponent() for decoding:

encodeURIComponent() handles all the characters that need encoding, including those that escape() didn't handle properly (like &, =, etc.).
decodeURIComponent() reverses the encoding done by encodeURIComponent().
Example:

javascript

var encoded = encodeURIComponent("Hello, world!");
console.log(encoded); // Output: "Hello%2C%20world%21"

var decoded = decodeURIComponent(encoded);
console.log(decoded); // Output: "Hello, world!"

TOP