Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to escape HTML in a string

Short answer

Replace the five special characters with their HTML entities. The ampersand goes first, otherwise the other replacements would be broken:

const escapeHtml = (text) =>
  text
    .replaceAll('&', '&')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
 
console.log(escapeHtml('<b>Tom & Jerry</b>'));

Output:

&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

Easier on a page: textContent

When you insert text into an element, use textContent. The browser shows it as is and never turns it into tags:

<p id="comment"></p>
<script>
  const userText = '<img src=x onerror=alert(1)>';
  document.getElementById('comment').textContent = userText;
</script>

Common mistake

Inserting user text through innerHTML without escaping lets anyone run their own code on your page:

// dangerous: the text becomes real HTML
element.innerHTML = userText;
 
// safe
element.textContent = userText;

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.