Full answer
Text in a file is stored as numbers. The character encoding is the table that maps those numbers to letters. If the browser guesses the wrong table, text such as the rupee sign or the euro sign turns into strange symbols. Declare the encoding with <meta charset="utf-8"> near the top of the head, and save the file as UTF-8. UTF-8 covers every language and is the standard choice.
Some characters have a special meaning in HTML. The < character starts a tag and & starts an entity. To show them as plain text, write an entity.
<for <>for >&for &"for a double quote inside an attribute value for a non-breaking space, which stops a line from breaking between two words©for the copyright sign
You can also write a character by its number: € or € for the euro sign. With UTF-8 you can type most characters directly, so numeric entities are only needed for the few reserved characters and for characters that are hard to type.
Entities matter for safety too. When user text is put into a page, it must be escaped, or text like <script> would run as code. Setting textContent in JavaScript treats the value as plain text, while innerHTML treats it as markup.
The first paragraph shows a euro sign and a rupee sign. The second shows the tags as visible text. The third keeps "Mr." and "Sharma" on one line. The last prints the tag characters literally, because textContent does not parse markup.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Entities</title>
</head>
<body>
<p id="a">Price: €20 or ₹1,700</p>
<p id="b">Write <h1> for a heading & <p> for a paragraph.</p>
<p id="c">Mr. Sharma</p>
<p id="d"></p>
<script>
document.getElementById("d").textContent = "<b>not bold</b>";
</script>
</body>
</html>Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
- <meta charset="utf-8"> belongs early in the head and must match how the file is saved.
- UTF-8 covers all languages.
- Entities like <, > and & show reserved characters as text.
- prevents a line break between two words.
- Escape or use textContent for user text to avoid injection.
Common mistakes
- Forgetting the charset declaration and seeing broken characters when the server does not send an encoding.
- Saving the file in an old encoding while the page declares UTF-8, which produces the same broken characters.
- Putting user input into innerHTML without escaping it, which allows script injection.
Follow-ups
- What happens if the charset is declared late in the head?
- What is the difference between textContent and innerHTML when inserting user text?
Tips
- State the pair that must match: the file is saved as UTF-8 and the page says utf-8.
- Name the five or six common entities and when is useful.