Convert characters to HTML entities
HTML is a markup language built heavily on a few reserved characters, most notably < (less than), > (greater than), and & (ampersand). When a browser parser encounters a <, it immediately assumes you are trying to open an HTML tag.
But what if you are writing a programming tutorial and actually want to show the user the string <div> on the screen? If you put that directly into your raw HTML file, the browser will interpret it as a real, invisible layout container instead of text.
To fix this, you must "encode" the reserved characters. You replace < with its HTML entity equivalent: <. The browser knows that < is meant to be displayed visually as a less-than sign, not executed as code.
Encoding is the absolute primary defense against Cross-Site Scripting (XSS) attacks. If your app allows users to post comments, a malicious user might submit their comment as <script>alert('hacked')</script>.
If you render that comment unencoded directly into the DOM, the browser will execute the attacker's script on the machine of every user who views the page. If you encode the comment into <script>..., the browser safely renders it as harmless, visible text.
A common UI bug in modern web frameworks is Double Encoding. Frameworks like React and Angular automatically HTML-encode all strings passed into JSX/templates by default.
If your backend database also encodes strings before saving them, the frontend will encode the already-encoded string. For example, & becomes & in the database, and React encodes it again to &amp;. The user then literally sees & printed on their screen instead of an ampersand.
Why must user input be HTML encoded before being rendered into the DOM?