How to encode quotes in HTML body?

元气小坏坏 提交于 2019-12-30 08:09:11

问题


Should I encode quotes (such as " and ' -> &rdquo; and &rsquo;) in my HTML body (e.g. convert <p>Matt's Stuff</p> to <p>Matt&rsquo;s Stuff</p>)? I was under the impression I should, but a co-worker said that it was no big deal. I'm dubious but I can't find anything that says it is forbidden. Am I mistaken? Is it a best-practice to encode? Or is it simply useless?


回答1:


Encoding quotation marks (") is in practice only needed if the're inside an attribute, however for the HTML code to be correct (passing HTML validation), you should always encode quotation marks as &quot;.

Apostrophes (') don't need escaping in HTML. In XHTML they should be encoded as &apos;.




回答2:


If you want your markup to be parsable as XML, you'll want to encode the following:

& => &amp;
< => &lt;
> => &gt;
" => &quot;
' => &apos;

Definitely do this in attributes whether you're trying to make your code XML compliant or not.




回答3:


Typicaly such isn't necessary unless you're placing such values into a tag's attribute (or other places where having quote marks would throw off parsing). In regular body text un-encoded will work fine.

<img src="..." alt="A &quot;quote mark&quot; in an alt attribute" />



回答4:


No, you only need to use character references for quotes (single or double) if you want to use them inside an attribute value declaration that uses the same quotes for the value declaration:

title="The sign says &quot;Matt's Stuff&quot;"
title='The sign says "Matt&#39;s Stuff"'

Both title values are The sign says "Matt's Stuff".



来源:https://stackoverflow.com/questions/1664208/how-to-encode-quotes-in-html-body

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