Sobes.tech
Senior

What symbols need to be escaped to protect against XSS attacks?

sobes.tech AI

Answer from AI

To protect against XSS attacks, it is necessary to escape special characters that can be interpreted by the browser as HTML or JavaScript. The main characters to escape:

  • & (ampersand) → &
  • < (less than) → &lt;
  • > (greater than) → &gt;
  • " (double quote) → &quot;
  • ' (single quote) → &#39;

Escaping these characters prevents malicious code injection into HTML or attributes.

Example in JavaScript:

function escapeHTML(str) {
  return str.replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
}

const userInput = '<script>alert("XSS")</script>';
const safeString = escapeHTML(userInput);
console.log(safeString); // &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

It is also important to use Content Security Policy (CSP) and avoid inserting unchecked HTML.

What symbols need to be escaped to protect against… - sobes.tech