7

This isn't working 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

That's not correct, if you enter the foo string on a 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 to properly decode the string?

  • possible duplicate of [JavaScript URL Decode function](http://stackoverflow.com/questions/4292914/javascript-url-decode-function) – j08691 Mar 13 '12 at 21:01

4 Answers4

13

Differences between decodeURI and decodeURIComponent

The main differences are:

  • encodeURI is intended to be used on the full URI.
  • encodeURIComponent is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

    So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.

    Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

    so in your case decodeURIComponent does the job

  • Daniele
    • 1,938
    • 16
    • 24
    vireshas
    • 806
    • 6
    • 19
    6

    Use decodeURIComponent:

    var decoded = decodeURIComponent(foo);
    

    decodeURI has some issues as you are seeing. decodeURIComponent is the best practice tool for this job.

    Joe
    • 80,724
    • 18
    • 127
    • 145
    4

    How about:

    unescape("Collection%3A 9 Bad Interviews With Former GOP Presidential Candidates")
    
    Kamyar Nazeri
    • 25,786
    • 15
    • 50
    • 87
    • I would not suggest using those: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_functions – Joe Mar 13 '12 at 21:10
    1

    The URI decodeURI() expects actually looks like this:

    Collection:%209%20Bad%20Interviews%20With%20Former%20GOP%20Presidential%20Candidates

    Check out this jsFiddle demonstrating what I mean. You'll want decodeURIComponent instead.

    Elliot Bonneville
    • 51,872
    • 23
    • 96
    • 123