← Back to all snippets
JAVASCRIPT

Safely Escape HTML for XSS Prevention in JavaScript

Protect your web applications from Cross-Site Scripting (XSS) by properly escaping HTML special characters before displaying user-generated content in JavaScript.

/**
 * Escapes HTML special characters in a string to prevent XSS attacks.
 * @param {string} str The string to escape.
 * @returns {string} The escaped string.
 */
function escapeHtml(str) {
  if (typeof str !== 'string') {
    return ''; // Or throw an error, depending on desired behavior
  }
  var div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;

  // Alternative using string replace for environments without DOM (e.g., Node.js, some templating engines)
  /*
  return str
    .replace(/&/g, "&")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
  */
}

// Example Usage:
const userInput = "<script>alert('You are hacked!');</script>";
const safeOutput = escapeHtml(userInput);

// This will render the script tag as plain text, not execute it.
document.getElementById('output').innerHTML = safeOutput;
// Expected output in HTML: &lt;script&gt;alert('You are hacked!');&lt;/script&gt;
How it works: This JavaScript function provides a robust way to prevent Cross-Site Scripting (XSS) vulnerabilities when displaying user-generated content. It works by escaping HTML special characters (`<`, `>`, `&`, `"`, `'`) into their respective HTML entities. By treating all user input as plain text and encoding it before inserting into the DOM, you ensure that malicious scripts cannot be injected and executed by the browser, rendering them harmless. The DOM-based method leveraging `createTextNode` is generally preferred for its safety and correctness.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs