AniUI Academy

Escape HTML entities

easyDOM & Utilities+150 XPPractice

The moment you build markup from a string, unescaped user input becomes an injection bug. Server-side renderers and template engines escape by default; when you build HTML by hand you have to do it yourself.

Implement escapeHtml(input). Replace, in this order, & with &amp;, < with &lt;, > with &gt;, " with &quot; and ' with &#39;. Every occurrence is replaced, not just the first.

The ampersand must be replaced first, so text that already contains an entity is escaped again: "&lt;" becomes "&amp;lt;". If input is null or undefined, return the empty string ""; any other non-string value is converted with String(input) before escaping.

Arguments

inputstring | null | undefined
The text to escape. null and undefined are treated as the empty string; other non-strings are converted with String(input) first.

Returns

string — A copy of the input with & < > " ' replaced by their HTML entity equivalents.

Examples

escapeHtml('<a href="x">Hi & bye</a>');
// => "&lt;a href=&quot;x&quot;&gt;Hi &amp; bye&lt;/a&gt;"

Angle brackets, quotes and ampersands are all replaced.

escapeHtml("&lt;");
// => "&amp;lt;"

The ampersand is escaped first, so an already-escaped entity is double-escaped.

escapeHtml(null);
// => ""

null and undefined both collapse to the empty string.

What it has to do

  • Replace all five characters & < > " ' with &amp; &lt; &gt; &quot; &#39; respectively.
  • Replace every occurrence, not just the first.
  • Escape ampersands first, so &lt; becomes &amp;lt;.
  • Return "" for null and undefined input.
  • Leave text with none of those characters untouched.

Notes

  • This is a one-way transform meant for text content inside HTML. For attribute values you should also escape ' (which this does), and for href/src you need a URL-aware escape on top.
  • &#39; is the numeric form of the apostrophe entity because the named &apos; is not part of HTML 4; the numeric form works everywhere.
Asked atMetaStripe

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.