HTML Entity Encoder: how it works and how to build one
Escape and unescape HTML entities like < and &. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
Escape user text before putting it in HTML, or turn " and ' back into readable characters. Optionally encode every non-ASCII character as a numeric entity.
When to use it
- Showing code snippets on a web page
- Cleaning CMS output
- Safely inserting user text
How to use it
- Choose Encode, Encode all non-ASCII, or Decode.
- Paste text or open a file.
- Copy the result.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/html-entities
How it works
Five characters have special meaning in HTML: & < > ” and ‘. Escaping replaces them with entities (& < …) so the browser shows them as text instead of reading them as markup. This is the core defence against cross-site scripting when you insert user text into HTML.
Decoding is easiest with the browser itself: put the text into a textarea element’s innerHTML and read back its value.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
entities.ts (ts)
const MAP: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
export const escapeHtml = (s: string, nonAscii = false) => {
const out = s.replace(/[&<>"']/g, (c) => MAP[c]);
return nonAscii ? out.replace(/[^\x00-\x7f]/gu, (c) => `&#${c.codePointAt(0)};`) : out;
};
export function decodeHtml(s: string) {
const t = document.createElement("textarea");
t.innerHTML = s; // the browser decodes every named and numeric entity
return t.value;
}
Make it production-ready
- In frameworks like React, text is escaped for you. Only escape by hand when building HTML strings.
Questions
Which characters are escaped?
& < > ” and ‘ are always escaped. The non-ASCII mode also escapes accented letters, symbols and emoji.
Free, runs in your browser, nothing is uploaded.