function sanitize(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
doc.querySelectorAll('*').forEach(node => {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('on')) {
node.removeAttribute(attr.name);
}
});
});
return doc.body.innerHTML;
}
const result = sanitize(`
<img src="x" onerror="console.log('on error from img')">
<button onclick="console.log('do bad stuff')">Trust me!</button>
`);
function sanitize(html) {
return html.replace(/(?!\s+)(on[a-z]+\s*=\s*)/gi, "nope=");
}
const result = sanitize(`
<img src="x" onerror="console.log('on error from img')">
<button onclick="console.log('do bad stuff')">Trust me!</button>
`);