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 &
'
is not a valid HTML reference entity. You should escape using '
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:
<
should be escaped. Usually <
is used for this. Technically, depending on HTML version, escaping is not always required, but it has always been good practice.&
should be escaped. Usually &
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."
as delimiter, it is customary to escape its occurrences using "
whereas for the Ascii apostrophe, the entity reference '
is defined in some HTML versions only, so it it safest to use the numeric reference '
(or '
).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” '
or '
to '
. I was somewhat surprised to here that '
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 '
reference.