In JavaScript, escaping and unescaping are operations that deal with converting special characters in strings to their respective encoded forms and vice versa. This is particularly useful when working with URLs, HTML, or other scenarios where special characters can cause issues.
1. Escape in JavaScript
Escaping a string means replacing certain characters (like spaces, punctuation, and non-ASCII characters) with a percent-encoded form, ensuring that they can be safely transmitted in URLs or used in various contexts.
Common escape methods:
encodeURIComponent(): Encodes a URI component by escaping special characters. It is the most common and modern method for escaping strings in JavaScript.
javascript
let str = "Hello World!";
let escapedStr = encodeURIComponent(str);
console.log(escapedStr); // "Hello%20World%21"
encodeURI(): Encodes a complete URI, but leaves certain characters like :, /, ?, and & intact, which are used in the structure of the URL.
javascript
let uri = "https://example.com/search?q=hello world";
let escapedUri = encodeURI(uri);
console.log(escapedUri); // "https://example.com/search?q=hello%20world"
2. Unescape in JavaScript
Unescaping a string means converting an encoded string back to its original form by replacing percent-encoded characters with their actual values.
Common unescape methods:
decodeURIComponent(): Decodes an escaped URI component, converting percent-encoded characters back to their original characters.
javascript
let escapedStr = "Hello%20World%21";
let unescapedStr = decodeURIComponent(escapedStr);
console.log(unescapedStr); // "Hello World!"
decodeURI(): Decodes a complete URI, but leaves characters like :, /, ?, and & intact.
javascript
let escapedUri = "https://example.com/search?q=hello%20world";
let unescapedUri = decodeURI(escapedUri);
console.log(unescapedUri); // "https://example.com/search?q=hello world"
Deprecated Methods (Avoid):
escape(): This method is deprecated and should not be used in modern JavaScript. It was used to escape non-ASCII characters, but it doesn't handle some characters like + and # properly for URIs.
unescape(): This method is also deprecated and was used to decode strings that were previously escaped with the escape() function.