Skip to the code
cf.

Escape HTML

Write escapeHtml(value). It returns value as a string that's safe to put inside HTML, as element content or inside a quoted attribute value.

Replace each of these five characters with its character reference: & with &amp;, < with &lt;, > with &gt;, " with &quot;, and ' with &#39;. Replace every occurrence, each exactly once, and leave every other character as it is. Text that already looks escaped is escaped again: &lt; becomes &amp;lt;.

If value isn't a string, convert it with String first.

escapeHtml('<a href="x">Tom & Jerry</a>');
// '&lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;'
escapeHtml("It's 5 > 3"); // "It&#39;s 5 &gt; 3"
escapeHtml(42);           // "42"

What the tests check

  1. escapes &, <, and >
    expect(escapeHtml("<b>Tom & Jerry</b>")).toBe("&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;");
    
  2. escapes double and single quotes
    expect(escapeHtml('"it\'s"')).toBe("&quot;it&#39;s&quot;");
    expect(escapeHtml('<a title="x">')).toBe("&lt;a title=&quot;x&quot;&gt;");
    
  3. replaces every occurrence, not only the first
    expect(escapeHtml("a<b<c>>d&&e")).toBe("a&lt;b&lt;c&gt;&gt;d&amp;&amp;e");
    
  4. escapes each character exactly once
    expect(escapeHtml("<")).toBe("&lt;");
    expect(escapeHtml('"&"')).toBe("&quot;&amp;&quot;");
    expect(escapeHtml("1 > 0")).toBe("1 &gt; 0");
    
  5. escapes text that already looks escaped
    expect(escapeHtml("&lt;b&gt; &amp;")).toBe("&amp;lt;b&amp;gt; &amp;amp;");
    
  6. leaves every other character alone
    expect(escapeHtml("Café / 50% off = {deal} #1")).toBe("Café / 50% off = {deal} #1");
    expect(escapeHtml("")).toBe("");
    
  7. converts other values with String first
    expect(escapeHtml(42)).toBe("42");
    expect(escapeHtml(null)).toBe("null");
    expect(escapeHtml({ toString() { return "<i>"; } })).toBe("&lt;i&gt;");
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).