CodeBlanks Logo Icon CodeBlanks

Input sanitization

JavaScript course · Expert · Lesson 29/63

Learn to prevent XSS by sanitizing input and encoding output.

What is HTML escaping?

When you write user-supplied text to the page as HTML, you must escape it. This turns special characters like <, >, & and " into HTML entities.

The browser then treats them as plain text, not as tag openings. Proper escaping is the most basic defense against XSS.

Output encoding with textContent

The safest output encoding method is to use textContent. This property does not interpret the value as HTML; it writes it as plain text.

So el.textContent = userInput never treats the input as a tag, whatever it contains. Prefer textContent over innerHTML whenever you can; you may not even need an escape function.

Exercise Write the escapeHtml function

Write a function escapeHtml, parameter str. First replace & with str.replace(/&/g, '&amp;'), then < with .replace(/</g, '&lt;') and > with .replace(/>/g, '&gt;'). Return the result.

Show example solution
First & then < then > and return the result.
Example solution:
function escapeHtml(str) {
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

Test yourself

  1. Which is what an HTML escape operation does?

    • Run the string with eval
    • Turn special characters into HTML entities
    • Encode the string with base64
    • Convert the string to lowercase
    Show answer

    Turn special characters into HTML entities — Correct! Escaping turns special characters into HTML entities.

  2. Turn a character into an HTML entity

    function escapeHtml(str) {
      return str.replace(/</g, '____');
    }
    Show answer
    function escapeHtml(str) {
      return str.replace(/</g, '&lt;');
    }
  3. Match each character with its entity

    <
    &lt;
    >
    &gt;
    &
    &amp;
    "
    &quot;

All lessons in Expert