HTML encode and decode functions in JavaScript
Two practical JavaScript functions for encoding and decoding HTML text safely in web pages.
If you print user input onto the page as-is, any HTML tags inside it are executed by the browser as code. That ranges from broken layout to script injection. Encoding turns those tags into harmless text; decoding does the reverse.
The two functions below use the browser's own parser. Hand-written replacement lists (this for &, that for <…) are always incomplete; DOMParser applies the full HTML ruleset, so nothing slips through.
Where you apply it matters: encode when displaying, not when storing. Keeping the raw value lets you reuse it later in another context — a mobile app, an API, an e-mail.
function htmlDecode(encoded_html) {
var htmlDoc = new DOMParser().parseFromString(encoded_html, "text/html");
return htmlDoc.documentElement.textContent;
}
function htmlEncode(html_string) {
var htmlDoc = new DOMParser().parseFromString("", "text/html");
htmlDoc.documentElement.textContent = html_string;
return htmlDoc.documentElement.innerHTML;
}
Short guide
When to use it
HTML encode/decode is used to display user input safely, store editor output or render API content correctly. In admin panels it looks like a small detail, but it directly affects security and readability.
What to watch
- Do not print user input directly into HTML.
- Do not confuse encoding with sanitizing; they solve different parts of the problem.
- Make sure the same value is not encoded twice, producing visible < style output.
Common mistake
The common mistake is treating encoding as a full security filter. XSS prevention needs context-aware encoding, sanitizing and validation together.
Where this example helps
Small helper snippets like this save time in web applications, mobile app backends, admin panels and API projects. The important part is not copying the example blindly, but adapting it to your data format, security needs and performance expectations.