我是否在< a href ...>中编码&符号? [英] Do I encode ampersands in <a href...>?

查看:78
本文介绍了我是否在< a href ...>中编码&符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写自动生成HTML的代码,并且我希望它能够正确编码。

I'm writing code that automatically generates HTML, and I want it to encode things properly.

假设我生成了以下URL的链接:

Say I'm generating a link to the following URL:

http://www.google.com/search?rls=en&q=stack+overflow

我假定所有属性值都应该是HTML编码的。 (如果我错了,请纠正我。)所以这意味着如果我将上面的URL放到锚标签中,我应该将&符号编码为& amp; ,如下所示:

I'm assuming that all attribute values should be HTML-encoded. (Please correct me if I'm wrong.) So that means if I'm putting the above URL into an anchor tag, I should encode the ampersand as &, like this:

<a href="http://www.google.com/search?rls=en&amp;q=stack+overflow">

是否正确?

Is that correct?

推荐答案

是的。 HTML实体在HTML属性内被解析,并且一个流浪& 会产生歧义。这就是为什么您应该始终在全部内写入& amp; 而不是& HTML属性。

Yes, it is. HTML entities are parsed inside HTML attributes, and a stray & would create an ambiguity. That's why you should always write &amp; instead of just & inside all HTML attributes.

也就是说,只有& 和引号需要编码。如果您的属性中包含特殊字符(如é),则无需对这些字符进行编码以满足HTML解析器的需要。

That said, only & and quotes need to be encoded. If you have special characters like é in your attribute, you don't need to encode those to satisfy the HTML parser.

过去,URL需要使用非ASCII字符进行特殊处理,例如é。你必须使用百分号转义符对它们进行编码,在这种情况下,它会给出%C3%A9 ,因为它们是由 RFC 1738 。但是,RFC 1738已被 RFC 3986 (URI,统一资源标识符)和 RFC 3987 (IRI,国际化资源标识符),。因此,现在可以安全地在网址中包含非ASCII字符,不管是百分比编码还是非编码。

It used to be the case that URLs needed special treatment with non-ASCII characters, like é. You had to encode those using percent-escapes, and in this case it would give %C3%A9, because they were defined by RFC 1738. However, RFC 1738 has been superseded by RFC 3986 (URIs, Uniform Resource Identifiers) and RFC 3987 (IRIs, Internationalized Resource Identifiers), on which the WhatWG based its work to define how browsers should behave when they see an URL with non-ASCII characters in it since HTML5. It's therefore now safe to include non-ASCII characters in URLs, percent-encoded or not.

这篇关于我是否在&lt; a href ...&gt;中编码&符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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