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.
CodePudding user response:
No
> encodeURIComponent('%')
'%'
> encodeURIComponent(encodeURIComponent('%'))
'%25'
> decodeURIComponent('%25')
'%'
> decodeURIComponent(decodeURIComponent('%25'))
'%'
> decodeURIComponent('%25') === decodeURIComponent(decodeURIComponent('%25'))
false
CodePudding user response:
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 = '%21';
console.log(decodeURIComponent(x), decodeURIComponent(decodeURIComponent(x)));
%21
→ !
→ !
Any given string is either encoded in a specific format or is plain text. You cannot guess what it is supposed to be. !
could either be the plaintext string "!", 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.