escapeHTML
Escapes special HTML characters to their corresponding HTML entities.
1/**
2 * Escapes special HTML characters to their corresponding HTML entities.
3 *
4 * @param str - The input string to escape.
5 * @returns The escaped HTML string.
6 */
7export function escapeHTML(str: string): string {
8 return str.replace(/[&<>"']/g, char =>
9 ({
10 '&': '&',
11 '<': '<',
12 '>': '>',
13 '"': '"',
14 "'": ''',
15 }[char] || char)
16 );
17}
Prevents HTML Injection
Escapes dangerous characters that could otherwise be interpreted as HTML, reducing XSS attack vectors.
Minimal and Efficient
Uses a concise
replace
operation with a fast lookup map, ensuring high performance even for large strings.Preserves Original Text Structure
Only transforms special characters, leaving all other content untouched and readable.
Works in All Environments
Pure JavaScript implementation that doesn't depend on browser-specific APIs or libraries.
Tests | Examples
1test('escapeHTML - escapes all basic HTML characters', () => {
2 expect(escapeHTML('<div class="test">Hello & Goodbye</div>')).toBe(
3 '<div class="test">Hello & Goodbye</div>'
4 );
5});
6
7test('escapeHTML - escapes single quote', () => {
8 expect(escapeHTML(`It's a test`)).toBe('It's a test');
9});
10
11test('escapeHTML - leaves string with no HTML characters unchanged', () => {
12 expect(escapeHTML('Plain text')).toBe('Plain text');
13});
14
15test('escapeHTML - handles empty string', () => {
16 expect(escapeHTML('')).toBe('');
17});
18
19test('escapeHTML - escapes only necessary characters', () => {
20 expect(escapeHTML('<a href="#">Link</a>')).toBe(
21 '<a href="#">Link</a>'
22 );
23});
Common Use Cases
Sanitizing User Input
Escape content before injecting it into the DOM to prevent code execution.
Displaying Raw HTML as Text
Show actual HTML code snippets (e.g.,
<div>
) in tutorials, documentation, or editors.Log or Debug Output
Safely render user-generated or server-returned HTML in a debug panel.
Templating Engines
Prevent auto-rendered content in templated views from breaking the layout or introducing vulnerabilities.