HTML Escape is the process of converting special HTML characters (like <, >, &, ") into HTML entities (like <, >, &, ").
Unescape is the reverse process, converting HTML entities back to their original characters.
Why Do We Need HTML Escaping?
- Prevent XSS (Cross-Site Scripting): Escaping is the first line of defense against XSS attacks. It prevents malicious HTML/JavaScript injection and is essential when displaying user-generated content.
- Display HTML Code as Text: Show HTML examples in documentation, render code snippets on web pages, or debug template engines.
- Data Serialization: Safely embed HTML in JSON/XML, prepare content for API responses, or store HTML in databases.
- Email & Header Safety: Escape special characters in email subjects, prepare data for HTTP headers, or handle form data correctly.
Entity Format Comparison
| Character | Named Entity | Decimal Entity | Hex Entity |
|---|---|---|---|
| < | < | < | < |
| > | > | > | > |
| & | & | & | & |
| " | " | " | " |
| ' | ' | ' | ' |
Code Examples
JavaScript (Browser)
// Escape HTML
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, m => map[m]);
}
// Unescape HTML
function unescapeHtml(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.documentElement.textContent;
}
// Usage
const escaped = escapeHtml('<script>alert("XSS")</script>');
console.log(escaped);
// <script>alert("XSS")</script>Node.js (using 'he' library)
const he = require('he');
// Encode
const encoded = he.encode('<div class="test">Hello & goodbye</div>');
console.log(encoded);
// <div class="test">Hello & goodbye</div>
// Decode
const decoded = he.decode('<div>Hello</div>');
console.log(decoded); // <div>Hello</div>
// Different formats
he.encode('<tag>', { useNamedReferences: true }); // <tag>
he.encode('<tag>', { decimal: true }); // <tag>
he.encode('<tag>', { hexadecimal: true }); // <tag>Python
import html
# Escape
escaped = html.escape('<script>alert("XSS")</script>')
print(escaped)
# <script>alert("XSS")</script>
# Unescape
unescaped = html.unescape('<div>Hello</div>')
print(unescaped) # <div>Hello</div>Security Best Practices
⚠️ Important Security Notes:
- Escaping is NOT Enough: Combine with Content Security Policy (CSP) and backend validation.
- Context Matters: Use appropriate escaping for HTML content, JavaScript strings, URLs, and SQL.
- Don't Trust User Input: Always validate and sanitize on both client and server side.
- Use Framework Built-ins: React, Vue, and Angular escape by default—leverage these features.
Common Use Cases
- XSS Prevention: Escape user input before displaying:
<script>alert('XSS')</script>→<script>alert('XSS')</script> - Displaying Code: Show HTML code examples on web pages by escaping tags.
- JSON with HTML: Prepare HTML fragments for JSON serialization.
- Email Content: Escape special characters in email subjects and headers.
- Template Debugging: Unescape rendered template output to see actual HTML.
HTML 이스케이프는 웹 보안 및 데이터 표시에 필수적입니다. 보안 감사 중 수많은 XSS 취약점을 처리하고 사용자 생성 콘텐츠를 안전하게 표시해야 할 필요성 때문에 이 도구를 만들었습니다. 양식 입력을 정리하든, 템플릿 엔진을 디버깅하든, JSON/XML 직렬화를 위한 데이터를 준비하든, 웹 보안 개념을 가르치든, 적절한 HTML 엔티티 인코딩은 필수적입니다. 이 도구는 세 가지 엔티티 형식을 지원합니다: 명명된 엔티티(<, >), 10진수 엔티티(<, >) 및 16진수 엔티티(<, >)—각각 다른 상황에서 유용합니다. 모든 처리는 브라우저의 클라이언트 측에서 이루어지므로 서버에 데이터를 보내지 않고도 민감한 콘텐츠를 안전하게 처리할 수 있습니다.
How to Use
이스케이프의 경우: 특수 문자가 포함된 HTML 또는 텍스트를 입력 패널에 붙여넣습니다. 도구는 <, >, &, \", ' 같은 문자를 실시간으로 HTML 엔티티로 자동 변환합니다. 선호하는 엔티티 형식을 선택하세요: 명명된(가장 읽기 쉬움, 예: &), 10진수(광범위한 호환성, 예: &), 또는 16진수(컴팩트, 예: &). '줄 바꿈 유지'를 토글하여 줄 바꿈을 유지하거나 제거합니다. 언이스케이프의 경우: 엔티티가 포함된 HTML을 붙여넣으면 도구가 원래 문자로 디코딩합니다. '모든 문자 인코딩' 옵션은 특수 문자가 아닌 문자도 이스케이프하여 최대 호환성을 위해 유용합니다.
Common Use Cases
XSS 방지
표시하기 전에 사용자 입력을 이스케이프: '<script>alert(XSS)</script>'가 '<script>alert(XSS)</script>'가 됩니다.
템플릿 디버깅
렌더링된 템플릿 출력을 언이스케이프하여 실제로 생성된 HTML을 확인합니다.
JSON 문자열 이스케이프
따옴표와 특수 문자를 이스케이프하여 JSON 직렬화를 위한 HTML 조각을 준비합니다.
코드 표시
태그를 이스케이프하여 웹 페이지에 HTML 코드 예제를 텍스트로 표시합니다.
이메일 HTML
이메일 제목 줄 또는 헤더의 특수 문자를 이스케이프합니다.
데이터베이스 저장
렌더링 문제를 방지하기 위해 텍스트 필드에 저장하기 전에 HTML을 이스케이프합니다.
Limitations & Important Notes
이 도구는 HTML5 사양에 정의된 HTML 엔티티를 처리합니다. 잠재적으로 위험한 HTML 속성(onclick, onerror 등) 또는 JavaScript 코드를 제거하거나 정리하지 않으며 문자 표현만 이스케이프합니다. 진정한 XSS 방지를 위해 이스케이프를 콘텐츠 보안 정책(CSP) 및 입력 검증과 결합하세요. 도구는 UTF-8 인코딩을 가정합니다. 다른 인코딩은 예기치 않은 결과를 생성할 수 있습니다. 매우 큰 문서(>5MB)의 경우 브라우저 메모리 제한으로 인해 속도가 느려질 수 있습니다. 엔티티 인코딩은 텍스트 크기를 증가시킵니다. 대역폭 제약이 있는 시나리오에는 적합하지 않습니다.