Decode HTML entities in one pass
Content from a CMS or an RSS feed arrives entity-encoded, and you have to decode it before you can search it, count its characters, or send it somewhere that is not HTML. Doing it with repeated replaces creates a real security bug: decode & first and then scan again, and the input &lt; turns into <, which the author explicitly escaped.
Implement unescapeHtml(input). It decodes, in a single left-to-right pass over the string, any entity matching &name;, { or .
The named entities you must support are exactly & to &, < to <, > to >, " to ", ' to ' and to a normal space. Numeric entities are decimal (') or hexadecimal with a lower or upper case x (/), and decode with String.fromCodePoint of that value. Any entity you do not recognise — ½, ©right; — is left in the output exactly as written.
Because it is one pass, text produced by decoding is never rescanned: "&lt;" decodes to "<" and stops there. If input is null or undefined, return the empty string "".
What it has to do
- Decode
&,<,>,",'and , with becoming a normal space. - Decode decimal
&#NN;and hexadecimal&#xNN;entities, case-insensitively on thex. - Leave unrecognised entities untouched.
- Decode in a single pass, so
&lt;becomes<and not<. - Return
""fornullandundefined.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.