AniUI Academy
easy+150 XPPractice

Escape HTML entities

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.

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.

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.