escaping inside html tag attribute value

后端 未结 2 1578
耶瑟儿~
耶瑟儿~ 2020-12-29 23:41

I am having trouble understanding how escaping works inside html tag attribute values that are javascript.

I was lead to believe that you should always escape &

相关标签:
2条回答
  • 2020-12-30 00:13

    ' is not a valid HTML reference entity. You should escape using '

    0 讨论(0)
  • 2020-12-30 00:32

    There are two types of “escapes” involved here, HTML and JavaScript. When interpreting an HTML document, the HTML escapes are parsed first.

    As far as HTML is considered, the rules within an attribute value are the same as elsewhere plus one additional rule:

    • The less-than character < should be escaped. Usually &lt; is used for this. Technically, depending on HTML version, escaping is not always required, but it has always been good practice.
    • The ampersand & should be escaped. Usually &amp; is used for this. This, too, is not always obligatory, but it is simpler to do it always than to learn and remember when it is required.
    • The character that is used as delimiters around the attribute value must be escaped inside it. If you use the Ascii quotation mark " as delimiter, it is customary to escape its occurrences using &quot; whereas for the Ascii apostrophe, the entity reference &apos; is defined in some HTML versions only, so it it safest to use the numeric reference &#39; (or &#x27;).

    You can escape > (or any other data character) if you like, but it is never needed.

    On the JavaScript side, there are some escape mechanisms (with \) in string literals. But these are a different issue, and not relevant in your case.

    In your example, on a browser that conforms to current specifications, the JavaScript interpreter sees exactly the same code alert('Hello');. The browser has “unescaped” &apos; or &#39; to '. I was somewhat surprised to here that &apos; is not universally supported these days, but it’s not an issue: there is seldom any need to escape the Ascii apostrophe in HTML (escaping is only needed within attribute values and only if you use the Ascii apostrophe as its delimiter), and when there is, you can use the &#39; reference.

    0 讨论(0)
提交回复
热议问题