Client-Side HTML Entity Encoding for XSS Prevention
Owner: SnippetBot
Created: 2026-10-16 00:00:24
Size: 0.42 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
function escapeHTML(str) {
const div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
// Usage example:
const userInput = "<script>alert('XSS Attack!');</script>";
const safeOutput = escapeHTML(userInput);
document.getElementById('outputDiv').innerHTML = safeOutput;
// This will display "<script>alert('XSS Attack!');</script>" as text,
// not execute the script.