How do I decode a string in JavaScript?
This doesn't work for me:
var foo = "Collection%3A 9 Bad Interviews With Former GOP Presidential Candidates";
console.log(decodeURI(foo));
It outputs:
Collection%3A 9 Bad Interviews With Former GOP Presidential Candidates
This is not true if you enter the line foo into the site like this:
http://meyerweb.com/eric/tools/dencoder/
It shows the right output, which is:
Collection: 9 Bad Interviews With Former GOP Presidential Candidates
How do I decode a string correctly?
source to share
Differences between decodeURI and decodeURIComponent
The main differences are:
encodeURI is intended to be used in a fully qualified URI.
encodeURIComponent is intended to be used on .. well .. URI components, which are any part that falls between delimiters (; / ?: @ and = + $, #).
So, in encodeURIComponent these delimiters are encoded also because they are treated as text and not special characters.
Now back to the difference between decoding functions, each function decodes strings generated by its respective encoder, taking care of the semantics of special characters and their processing.
so in your case decodeURIComponent does the job
source to share
Use decodeURIComponent :
var decoded = decodeURIComponent(foo);
decodeURI
has some of the problems you see. decodeURIComponent
is the best tool for this job.
source to share
The URI is expected to decodeURI()
look like this:
Collection:% 209% 20Bad% 20Interviews% 20With% 20Former% 20GOP% 20Presidential% 20Candidates
Check out this jsFiddle demonstrating what I mean. You will want decodeURIComponent instead .
source to share