Why Escape HTML Characters?
In HTML, characters like <, >, and & are syntactically reserved for tags and references. Unescaped user inputs can trigger layout breaks or dangerous Cross-Site Scripting (XSS) vulnerabilities. Escaping them ensures raw code displays safely as plain text.
The Five XML/HTML Core Entities
&➡️&(Ampersand)<➡️<(Less-than)>➡️>(Greater-than)"➡️"(Double quotation)'➡️'(Single quotation / apostrophe)
What happens in the page
encodeEntities() walks the string one code point at a time and looks it up in a small named-entity table (&, <, >, ", and the common typographic marks), emitting either a named reference or a numeric one depending on the format you pick; a second switch decides whether only the reserved five characters are escaped or every non-ASCII character is escaped as well. decodeEntities() takes the opposite approach to correctness: it assigns the text to a detached textarea's innerHTML and reads the value back, borrowing the browser's own tokeniser as the reference implementation.
Where it breaks down
The named table is intentionally short, so uncommon entities come back as numeric references instead of names. Input that has already been escaped twice (&) unwinds one layer per click — there is no loop that keeps decoding until stable. The textarea trick cannot resolve entities inside script or style semantics, and code points above U+FFFF decode into surrogate pairs that a few legacy systems still reject.
Privacy: no data leaves this tab
Encoding and decoding both run against a detached DOM node in this tab, so the string never enters a network request — not even a font fetch, which is already deferred until after the page renders.
Frequently asked questions
Why escape anything at all?
The five reserved characters — ampersand, angle brackets and quotes — can end a tag or an attribute early, so they are escaped whenever text has to sit safely inside HTML markup.
Do Chinese or accented characters need escaping?
Not for a UTF-8 page; they display directly. Escaping them only matters when the receiving system cannot declare UTF-8, which is why the full-escape switch exists.
Why does one pass not fully decode?
Because layered escaping is normal in badly-built templates: each pass removes exactly one layer. Run it again until the output stops changing.