JAVASCRIPT

Sanitize HTML Output to Prevent XSS

Learn to prevent Cross-Site Scripting (XSS) attacks by properly escaping HTML special characters before displaying user-generated content in the browser.

function escapeHtml(str) {
  const div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
}

// Example Usage:
const userInput = "<script>alert('You are hacked!');</script>";
document.getElementById('output').innerHTML = escapeHtml(userInput);
// document.getElementById('output').textContent = userInput; // Alternative and often simpler if no HTML is intended
How it works: This JavaScript function `escapeHtml` prevents XSS by converting HTML special characters (like `<`, `>`, `&`, `"`, `'`) in user input into their HTML entities. It achieves this by creating a temporary `div` element, setting the user input as its text content (which automatically escapes characters), and then retrieving the `innerHTML`. This ensures that malicious scripts are rendered as text rather than executable code when displayed in the DOM. A simpler approach if only text is intended is to use `textContent` directly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs