了解解码URI的工作方式 [英] understanding how decodeURI works

查看:93
本文介绍了了解解码URI的工作方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取字符串的解码值.我注意到当我执行document.write()时,decodeURI(我未使用unescape的原因是我在不赞成使用unescape的地方读到了),但是警报仍然显示未解码的值.

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.

推荐答案

似乎您误解了

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

在您的示例中,uri不包含任何编码的URI数据. alert()仍显示HTML实体,因为Javascript警报仅适用于纯文本.使用document.write()时,浏览器会解释该变量并自动解析HTML实体(&#39;).

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;).

例如,以下是使用第一个示例作为基础的JS控制台的一些示例输出:

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"

您正在将HTML实体与URL编码的字符混淆. apostrophe的URL编码字符实际上是%27(&#39;是HTML实体).

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

因此,现在运行decodeURI(),将Unicode撇号替换为正确的URL编码版本,即可产生预期的输出.例如:

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"

这篇关于了解解码URI的工作方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆