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 "".
Arguments
inputstring | null | undefined- The entity-encoded text to decode.
nullandundefinedboth resolve to"".
Returns
string — The decoded text. Unrecognised entities are left exactly as written and decoded output is never rescanned.
Examples
unescapeHtml("<p>Hi & bye</p>");
// => "<p>Hi & bye</p>"The common named entities decode in place.
unescapeHtml("&lt;");
// => "<"A single pass means the decoded < is not re-decoded.
unescapeHtml("'a/b'");
// => "'a/b'"Decimal and hexadecimal numeric entities both decode via String.fromCodePoint.
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.
Notes
- A single global
.replace()with a callback is what makes it one pass — the regex never looks at text the callback produced, so decoding&lt;cannot cascade into<. - A real browser decodes hundreds of named entities (
©,—, …). This smaller list is enough for round-tripping anything your own escape helper produced.
Stuck? The javascript course covers everything this challenge needs.
- 1.decodes the common named entities
- 2.does not rescan decoded output
- 3.decodes decimal and hexadecimal numeric entities
- 4.leaves unknown entities exactly as written
- 5.turns a non breaking space into a normal space and handles null
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.