HTML Escaping User Input to Prevent XSS in JavaScript
Owner: SnippetBot
Created: 2026-10-03 00:00:34
Size: 2.15 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Escapes HTML special characters in a string to prevent Cross-Site Scripting (XSS) attacks.
* This function should be used when displaying user-generated content in HTML.
* It converts characters like <, >, &, ", ' to their HTML entity equivalents.
* @param {string} str - The input string to escape.
* @returns {string} The escaped string.
*/
function escapeHtml(str) {
const div = document.createElement('div');
// Using textContent property is the safest way to escape HTML.
// Assigning text to textContent automatically escapes HTML entities.
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
/**
* Alternative method using replace for specific known characters.
* Less robust than DOM-based escaping for complex scenarios, but useful for quick sanitization
* if DOM manipulation is not feasible or desired (e.g., in a Node.js context).
* @param {string} str - The input string to escape.
* @returns {string} The escaped string.
*/
function escapeHtmlManual(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// --- Example Usage ---
const userInput1 = "<script>alert('XSS Attack!');</script>";
const userInput2 = "User's profile & settings.";
const userInput3 = '<h1>Hello World!</h1>';
const safeOutput1 = escapeHtml(userInput1);
const safeOutput2 = escapeHtml(userInput2);
const safeOutput3 = escapeHtml(userInput3);
console.log('Original 1:', userInput1);
console.log('Escaped 1:', safeOutput1);
// document.getElementById('output1').innerHTML = safeOutput1;
console.log('Original 2:', userInput2);
console.log('Escaped 2:', safeOutput2);
// document.getElementById('output2').innerHTML = safeOutput2;
console.log('Original 3:', userInput3);
console.log('Escaped 3:', safeOutput3);
// document.getElementById('output3').innerHTML = safeOutput3;
const safeOutputManual1 = escapeHtmlManual(userInput1);
console.log('Manual Escaped 1:', safeOutputManual1);
/*
// To see the effect in HTML, uncomment the following (requires an HTML file):
// <div id="output1"></div>
// <div id="output2"></div>
// <div id="output3"></div>
*/