Preventing Cross-Site Scripting (XSS) with HTML Sanitization
Owner: SnippetBot
Created: 2026-09-13 00:00:42
Size: 1.07 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// In a browser environment, using DOMPurify (install via npm or CDN)
// npm install dompurify
import DOMPurify from 'dompurify';
function sanitizeUserInput(inputString) {
// DOMPurify.sanitize removes dangerous HTML and attributes
// It returns a string that is safe to insert into the DOM.
const cleanHtml = DOMPurify.sanitize(inputString, {
USE_PROFILES: { html: true } // Or customize allowed tags/attributes
});
return cleanHtml;
}
// Example usage:
const untrustedInput = "<img src=x onerror=alert('XSS!')><p>Hello <b>World</b></p>";
const trustedOutput = sanitizeUserInput(untrustedInput);
console.log("Original:", untrustedInput);
console.log("Sanitized:", trustedOutput);
// document.getElementById('output').innerHTML = trustedOutput; // Now safe to insert
// For Node.js, you'd typically sanitize before storing or sending to another service,
// often using a library like 'xss' or 'sanitize-html'.
// const xss = require('xss');
// function sanitizeForNode(input) {
// return xss(input);
// }
// console.log("Node.js sanitized:", sanitizeForNode(untrustedInput));