AniUI Academy
medium+250 XPPractice

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 &amp; first and then scan again, and the input &amp;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;, &#123; or &#x1F;.

The named entities you must support are exactly &amp; to &, &lt; to <, &gt; to >, &quot; to ", &apos; to ' and &nbsp; to a normal space. Numeric entities are decimal (&#39;) or hexadecimal with a lower or upper case x (&#x2F;), and decode with String.fromCodePoint of that value. Any entity you do not recognise — &frac12;, &copyright; — is left in the output exactly as written.

Because it is one pass, text produced by decoding is never rescanned: "&amp;lt;" decodes to "&lt;" and stops there. If input is null or undefined, return the empty string "".

What it has to do

  • Decode &amp;, &lt;, &gt;, &quot;, &apos; and &nbsp;, with &nbsp; becoming a normal space.
  • Decode decimal &#NN; and hexadecimal &#xNN; entities, case-insensitively on the x.
  • Leave unrecognised entities untouched.
  • Decode in a single pass, so &amp;lt; becomes &lt; and not <.
  • Return "" for null and undefined.

Your workspace

Try it yourself
Loading playground...

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.