Is Node decodeURIComponent idempotent?
Does...
decodeURIComponent(x) === decodeURIComponent(decodeURIComponent(x))
for any and all x
?
If not, is there an alternative that is idempotent? Was trying to think through if this was possible myself.
Is Node decodeURIComponent idempotent?
Does...
decodeURIComponent(x) === decodeURIComponent(decodeURIComponent(x))
for any and all x
?
If not, is there an alternative that is idempotent? Was trying to think through if this was possible myself.
No
> encodeURIComponent('%')
'%25'
> encodeURIComponent(encodeURIComponent('%'))
'%2525'
> decodeURIComponent('%2525')
'%25'
> decodeURIComponent(decodeURIComponent('%2525'))
'%'
> decodeURIComponent('%2525') === decodeURIComponent(decodeURIComponent('%2525'))
false
No. If the string decodes to a new sequence which itself can be interpreted as an encoded URI component, then it can be decoded again to a different string:
const x = '%2521';
console.log(decodeURIComponent(x), decodeURIComponent(decodeURIComponent(x)));
%2521
→ %21
→ !
Any given string is either encoded in a specific format or is plain text. You cannot guess what it is supposed to be. %21
could either be the plaintext string "%21", or a URL-encoded string representing "!". You need to know which it's supposed to be and interpreted it accordingly. That generally goes for any and all text encoding formats.