user34537
user34537

Reputation:

Why is `'` escaped in html libs?

With HTML I notice some libraries escape '. My question is why? The first time I thought maybe they did it just because but I seen more then one do it but not all. I can't remember what I looked at from the top of my head but the others i remember were &, <, >, ".

I know & is used for escape characters (such as to make &amp; which is &). < and > are escaped to not be confused for start/end tags and " is done so you can put " in tag attributes if you need to for some reason. But why '? Also am I missing any other characters that should be escaped?

Upvotes: 0

Views: 51

Answers (3)

Brad
Brad

Reputation: 163301

The single-quote mark is escaped because it can only be used as-is in certain contexts. When writing an escaping function, it is easier and faster to just always escape it, so you don't have to take into account the context.

For example, if you use double quotes " to denote an attribute value, you can use a single quote ' within it safely. However, if you use single quotes to denote the attribute value, you cannot.

Upvotes: 1

scott.korin
scott.korin

Reputation: 2597

In HTML, " and ' are interchangeable. Both can be used for setting the attribute for an element as well as used for denoting a string in JavaScript:

<img src="bob.png" />

<img src='bob.png' />

Upvotes: 2

Dai
Dai

Reputation: 155055

Because under HTML, the single-quote character ' can be used to delimit element attributes instead of the double-quote, like so:

<p class='something'></p>

However the character does not need to be escaped normally, but it's best to be safe.

Upvotes: 4

Related Questions