understanding how decodeURI works

谁说胖子不能爱 提交于 2019-12-25 02:12:05

问题


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.


回答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 (&#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"


来源:https://stackoverflow.com/questions/29157005/understanding-how-decodeuri-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!