escapeHtml
Escape HTML special characters to prevent XSS attacks.
API
escapeHtml
Return
| Argument | Description | Type |
|---|---|---|
string | Escaped string | string |
Parameters
| Parameter | Description | Type | Default |
|---|---|---|---|
string | String to escape | string | number | null | Required |
Example
Basic Usage
js
import { escapeHtml } from 'ranuts';
const html = '<script>alert("XSS")</script>';
const escaped = escapeHtml(html);
console.log(escaped); // '<script>alert("XSS")</script>'Escape Special Characters
js
import { escapeHtml } from 'ranuts';
console.log(escapeHtml('"hello"')); // '"hello"'
console.log(escapeHtml("'world'")); // ''world''
console.log(escapeHtml('a & b')); // 'a & b'
console.log(escapeHtml('<div>')); // '<div>'Handle Numbers and null
js
import { escapeHtml } from 'ranuts';
console.log(escapeHtml(123)); // '123'
console.log(escapeHtml(null)); // 'null'Prevent XSS Attacks
js
import { escapeHtml } from 'ranuts';
const userInput = '<img src=x onerror=alert(1)>';
const safe = escapeHtml(userInput);
document.getElementById('content').textContent = safe;
// Safe display, won't execute scriptNotes
Escaped characters: Escapes the following characters:
"→"'→'&→&<→<>→>
Type conversion: Non-string types are first converted to strings before escaping.
Security: Used to prevent XSS attacks, should be used when displaying user input content.
Performance: For strings that don't contain special characters, returns the original string directly.