In JavaScript, what is the difference between these?
escape()
/ unescape()
encodeuri()
/ decodeuri()
>
Just try encodeURI()
and encodeURIComponent()
yourself...
console.log(encodeURIComponent('@#$%^&*'));
Input: @#$%^&*
. Output: %40%23%24%25%5E%26*
. So, wait, what happened to *
? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent() and fixedEncodeURI(). Long-story...
escape()
: Do Not Use!!! To quote MDN escape() Documentation...Warning: Although escape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states:
... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code....
encodeURI()
: Do Not Use!!! Use fixedEncodeURI()
. To quote MDN encodeURI() Documentation...If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
encodeURIComponent()
: Do Not Use!!! Use fixedEncodeURIComponent()
. To quote the MDN encodeURIComponent() Documentation...To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
Then the question can be simplified: What's the difference between fixedEncodeURI()
and fixedEncodeURIComponent()
? fixedEncodeURIComponent()
encodes the following characters, while fixedEncodeURI()
does not: +@?=:#;,$&
.