// 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 = "
Hello World
"; 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));