问题
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's").text();
but still wondering why the original code doesn't work? It seems to be a pretty straightforward use case.
回答1:
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 ('
).
For example, here is some sample output from the JS console using your first example as a basis:
> var test = 'Hello's';
> decodeURI(test);
< "Hello's"
You are confusing HTML entities with URL-encoded characters. The URL-encoded character for apostrophe
is actually %27
('
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"
来源:https://stackoverflow.com/questions/29157005/understanding-how-decodeuri-works