JAVASCRIPT

HTML Escaping for XSS Prevention in JavaScript

Discover how to effectively escape user-supplied strings before rendering them in HTML to prevent Cross-Site Scripting (XSS) vulnerabilities in modern web applications.

/**
 * Escapes HTML entities 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
  }
  const div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
}

// --- Usage Example ---
const userInput = "<script>alert('XSS Attack!');</script>Hello & World '" ";
const safeOutput = escapeHtml(userInput);

console.log("Original Input:", userInput);
console.log("Safe Output (HTML Escaped):", safeOutput);

// If you were to insert this into the DOM:
// document.getElementById('output').innerHTML = safeOutput;
// The browser would render it as plain text, not execute the script.

// Example with potentially malicious attribute value
const maliciousAttribute = "\" onclick=\"alert('XSS via attribute!')\";
const safeAttribute = escapeHtml(maliciousAttribute);
console.log("Malicious Attribute:", maliciousAttribute);
console.log("Safe Attribute:", safeAttribute);
// document.getElementById('element').setAttribute('data-user', safeAttribute);
How it works: This JavaScript snippet provides a robust function, `escapeHtml`, to sanitize user-provided strings before they are rendered into the DOM. It works by creating a temporary `div` element, appending the raw string as a text node, and then extracting its `innerHTML`. This process automatically converts special HTML characters like `<`, `>`, `&`, `"`, and `'` into their respective HTML entities (e.g., `&lt;`, `&gt;`), effectively neutralizing any embedded scripts or malicious HTML and preventing Cross-Site Scripting (XSS) attacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs