Escape HTML entities to prevent Cross-Site Scripting attacks.
Code
General// Escape HTML entities to prevent XSS
const escapeHtml = (str) => str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
escapeHtml(userInput);Parameters
Untrusted user input (try a malicious payload)
What is XSS?
Cross-Site Scripting (XSS) occurs when untrusted data is included in a web page without proper escaping. An attacker can inject malicious scripts that execute in other users' browsers.
<!-- If userInput is: <script>alert('XSS')</script> -->
<div>Welcome, <script>alert('XSS')</script>!</div>
<!-- The script executes! -->
Why Escaping Works
| Character | Escaped | Why |
|---|---|---|
< | < | Prevents opening tags |
> | > | Prevents closing tags |
" | " | Prevents breaking out of attributes |
' | ' | Prevents breaking out of attributes |
& | & | Prevents entity injection |
After escaping, the browser displays the characters literally instead of interpreting them as HTML:
<div>Welcome, <script>alert('XSS')</script>!</div>
<!-- Shows: Welcome, <script>alert('XSS')</script>! -->
<!-- No script executes! -->
Alternative: Use textContent
When setting text (not HTML), use textContent instead of innerHTML:
// SAFE: textContent automatically escapes
element.textContent = userInput;
// DANGEROUS: innerHTML interprets HTML
element.innerHTML = userInput; // Never with untrusted input!
Common XSS Payloads
| Payload | Attack Vector |
|---|---|
<script>...</script> | Direct script execution |
<img src=x onerror=...> | Event handler injection |
<a href="javascript:..."> | JavaScript URL |
" onclick="..." | Attribute injection |
The Rule
Never insert untrusted data into HTML without escaping. Use textContent for text, escape for HTML contexts.
More JavaScript Snippets
Constant Time Compare
Compare two strings in constant time to prevent timing attacks. Unlike === which returns early on first mismatch, this compares all characters regardless of where differences occur.
FNV-1a Hash
Fast non-cryptographic hash function.
Generate Password
Generate a cryptographically secure random password with configurable options.
Hash SHA-256
Generate a SHA-256 hash of a string. SHA-256 produces a fixed 64-character hexadecimal output regardless of input size.
Parse JWT Payload
Extract and decode the payload from a JWT token without verification. Useful for reading claims like user ID, expiration time, and roles from tokens.
Simple String Hash
Generate a simple numeric hash from a string.