jquerydecodeuricomponent

understanding how decodeURI works


I am trying to get the decoded value for the string. I notice that decodeURI (i am not using unescape because i read somewhere that its deprecated) works when i do a document.write(), but the alert still shows the non-decoded value.

var uri = "Hello's ";
var dec = decodeURI(uri);
alert(dec);
document.write(dec);

I finally used the below code and things worked;

var strName = $('<div/>').html("Hello&#39;s").text();

but still wondering why the original code doesn't work? It seems to be a pretty straightforward use case.


Solution

  • It seems like you have misunderstood what the decodeURI() function does.

    In your example, uri does not contain any encoded URI data. The alert() still shows the HTML entities because Javascript alerts work on plaintext only. When you use document.write(), the browser interprets the variable and automatically parses the HTML entity (&#39;).

    For example, here is some sample output from the JS console using your first example as a basis:

    > var test = 'Hello&#39;s';
    > decodeURI(test);
    < "Hello&#39;s"
    

    You are confusing HTML entities with URL-encoded characters. The URL-encoded character for apostrophe is actually %27 (&#39; is the HTML entity).

    So now, running decodeURI() with the unicode apostrophe replaced by the correct URL-encoded version produces the expected output. For example:

    > var test = 'Hello%27s';
    > decodeURI(test);
    < "Hello's"