+ 4
When to use entities in HTML?
Hello everyone, I'm a beginner on HTML and CSS and I'm trying to develop good habits from the very beginning so I usually have a lot of questions about the basics :) I wonder if I should substitute every special character for an entity (when writing a paragraph in HTML) or just some of them. I was told that ampersand and inequality sign should be replaced with entities every single time, but what about other special characters like exclamation mark, quotation mark or hyphen? Is it correct to replace all of them as well?
3 Antworten
+ 3
I wouldn't replace with an entity unless it invalidates the HTML. Entities look ugly and are difficult to read. The simplest and best teacher for what is and is not requiring an HTML entity is an HTML validator.
The most trustworthy validator is at:
https://validator.w3.org/
Not all entities are needed to make valid HTML. For example, " most-often isn't needed. It makes the HTML look more cryptic to developers, adds more bytes to the download size, and doesn't make the HTML any more valid. It is bad in every way.
The validator will ensure that those special characters don't introduce any character encoding issues or other HTML validity problems.
Trust the validator more than what any person says including myself. I'm fairly confident with a few pointers, though.
Out of the specific characters you mentioned, exclamation marks, regular quotation marks, and regular hyphens shouldn't require entities. There are some similar but more special characters that require entities. There are directed quotes(right and left), left and right single quote/apostrophe, a long dash or hyphen(longer than the regular hyphen) that probably need entities but the validator should point this out. An ampersand should always be an entity like & in HTML.
< and > signs in text nodes must be replaced with entities like &lt; and &gt; too. There are different rules for when < and > are used in JavaScript and CSS, though.
Also note that URL formats need to be encoded differently than text nodes. Regular double quotes wrap an attribute's value so a quote within it needs to be escaped like \".
+ 14
Here's an article which explains how and when to use HTML entities.
https://www.w3schools.com/html/html_entities.asp
+ 2
Thank you so much for your replies!