JavaScript Escape HTML Function
Escaping HTML in JavaScript is a critical security practice used to prevent Cross-Site Scripting (XSS) attacks. Whenever user input is displayed on a webpage, it must be sanitized to ensure that HTML tags and scripts are not executed by the browser.
This page explains what HTML escaping is, why it matters, and how to implement a reusable JavaScript escape HTML function with practical examples
What Is HTML Escaping?
HTML escaping is the process of converting special characters such as <, >, ", and & into safe HTML entities so they are displayed as text instead of executed as code.
Example:
<script>alert('XSS')</script>Escaped output:
<script>alert('XSS')</script>Characters That Must Be Escaped
<Less Than Sign -<>Greater Than Sign ->&Ampersand -&"Double Quote -"'Single Quote -'
Why Escaping HTML Is Important
- Prevents XSS vulnerabilities
- Protects user data and sessions
- Required when displaying user-generated content
When Should You Escape HTML?
You should always escape HTML when inserting dynamic text using.
- Displaying user input
- Rendering comments, messages, reviews
- Outputting data inside HTML
innerHTML
Do NOT escape when:
You intentionally render trusted HTML. You use textContent instead of innerHTML
element.textContent = userInput;Live Demo:
Here is a simple and reusable JavaScript function to escape HTML:
const escapeHTML = (str) => {
if (typeof str !== "string") return str;
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
Usage Example:
const userInput = "<h1>Hello</h1>";
const safeText = escapeHTML(userInput);
const preview = document.getElementById("preview-text");
preview.innerHTML = safeText;Live Demo:
You can also escape HTML using the browser DOM API
const escapeHTMLDOM = (str) => {
const div = document.createElement("div");
div.textContent = str;
return div.innerHTML;
};
Usage:
const userInput = "<div>HTML</div>";
const safeText = escapeHTMLDOM(userInput);
const preview = document.getElementById("preview-dom-text");
preview.innerHTML = safeText;Why This Works
textContentautomatically escapes HTML- Avoids manual regex replacements
- Safer for complex strings
Live Demo:
Sometimes you need to convert escaped HTML entities back into normal text. This process, called unescaping, turns < back into <, > back into >, and so on. It is useful when you receive user input or stored data that was previously escaped, and you want to display it as readable text without executing it as HTML.
const unescapeHTML = (str) => {
const textarea = document.createElement("textarea");
textarea.innerHTML = str;
return textarea.value;
};
Usage:
<textarea id="input" placeholder="Enter HTML here"></textarea>
<button onclick="runEscape()">Escape HTML</button>
<pre id="output"></pre>const runEscape = () => {
const value = document.getElementById("input").value;
document.getElementById("output").textContent = unescapeHTML(value);
};