I want to display text to HTML using a JavaScript function, but how can I escape HTML special characters in JavaScript? Is there an API or built-in method for this?
Hey, I’ve worked with frontend JavaScript for a while, and one of the simplest and safest ways I’ve found for javascript escape html
is to lean on the browser’s built-in DOM methods.
You can use something like this:
function escapeHtml(str) {
const div = document.createElement('div');
if (str) {
div.innerText = str;
div.textContent = str; // fallback, both are safe
}
return div.innerHTML;
}
const unsafeString = '<div>This is "unsafe" text!</div>';
const safeString = escapeHtml(unsafeString);
console.log(safeString); // <div>This is "unsafe" text!</div>
Why this works:
- Browser-safe: You let the browser handle escaping all the HTML-sensitive characters (
<
,>
,&
,'
,"
). - Simple & reliable: No need to manually handle replacements or maintain mappings.
- Cross-browser: Works smoothly across all modern environments.
If you’re just starting or want a no-fuss solution, this is my go-to recommendation.
Building on Dimple’s point — I’ve worked in cases where we needed finer control or worked in older JavaScript environments, and here’s where a custom mapping approach for javascript escape html
shines.
Here’s an example of doing it manually:
function escapeHtml(str) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return str.replace(/[&<>"']/g, m => map[m]);
}
const unsafeString = '<div>This is "unsafe" text!</div>';
const safeString = escapeHtml(unsafeString);
console.log(safeString); // <div>This is "unsafe" text!</div>
Why this works:
- Full control: You decide exactly what gets escaped and how.
- Compatibility: Works even if you’re targeting environments where
innerText
ortextContent
aren’t reliable. - Customizable: You can extend this to handle special cases or add/remove mappings as needed.
If you need precision or are working in strict legacy setups, this manual approach can be really handy.
Great points above! From my experience in larger projects, especially where edge cases pop up, using a dedicated library for javascript escape html
is the most robust and future-proof approach.
One solid choice is the he (HTML Entities) library:
npm install he
Then in your code:
const he = require('he');
const unsafeString = '<div>This is "unsafe" text!</div>';
const safeString = he.escape(unsafeString);
console.log(safeString); // <div>This is "unsafe" text!</div>
Why this works:
- Comprehensive: Handles complex Unicode, edge cases, and less common entities beyond the usual suspects.
- Convenient: Well-maintained and tested — you don’t have to reinvent the wheel.
- Scalable: Perfect if you’re already using npm or bundlers and want to integrate professional-level solutions.
For production-grade projects or when you want peace of mind, libraries like he
are the way to go.