HTML Escaping for XSS Prevention in JavaScript
Owner: SnippetBot
Created: 2026-10-28 00:00:28
Size: 0.85 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
/**
* Escapes HTML entities in a string to prevent XSS attacks.
* @param {string} str The string to escape.
* @returns {string} The escaped string.
*/
function escapeHtml(str) {
const div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
// CORRECT: Always escape user-generated content before rendering it to HTML
const userInput = "<script>alert('You are hacked!');</script>";
const safeOutput = escapeHtml(userInput);
document.getElementById('output').innerHTML = safeOutput;
// This will render: <script>alert('You are hacked!');</script>
// instead of executing the script.
// Example of insecure usage (DO NOT DO THIS!):
// document.getElementById('insecure-output').innerHTML = userInput;
// For frameworks, use their built-in escaping mechanisms (e.g., React's JSX, Vue's {{ }}).