HTML escape characters | Example code

What characters need to be escaped in HTML?

Answer: It depends upon the context. Some possible contexts in HTML:

  • Document body
  • Inside common attributes
  • Inside script tags
  • Inside style tags

Inside of an element, this just includes the entity escape ampersand & and the element delimiter less-than and greater-than signs < >:

These are three main characters which should be always escaped in your HTML and XML files,

& becomes &amp;
< becomes &lt;
> becomes &gt;

Inside of attribute values you must also escape the quote character you’re using:

" becomes &quot;
' becomes &#39;

How to HTML escape characters example

HTML example code escape and unescape char using JavaScript.

<!DOCTYPE html>

  <div class="half first"><textarea id="input" placeholder='Paste your HTML in here...' spellcheck="false" autofocus></textarea></div>

  <div class="middle">
    <select id="method">
      <option value="escape">escape</option>
      <option value="unescape">unescape</option>

  <div class="half last"><textarea id="output" placeholder='Output...' spellcheck="false"></textarea></div>
    // Escape & Unescape HTML:
    (function() {
      var escapeEl = document.createElement('textarea');

      window.escapeHTML = function(html) {
        escapeEl.textContent = html;
        return escapeEl.innerHTML;

      window.unescapeHTML = function(html) {
        escapeEl.innerHTML = html;
        return escapeEl.textContent;

// getElementById shortcut:
var $ = function(id, scopeEl) {
  return (scopeEl || document).getElementById(id);

// Grab the needed elements:
var inputEl = $('input');
var outputEl = $('output');
var methodToggleEl = $('method');

// Handle input:
function inputHandler() {
  outputEl.value = window[methodToggleEl.value + 'HTML'](inputEl.value);
methodToggleEl.onchange = inputEl.oninput = inputHandler;


HTML escape characters

Some Useful HTML Character Entities

ResultDescriptionEntity NameEntity Number
non-breaking space&nbsp;&#160;
<less than&lt;&#60;
>greater than&gt;&#62;
double quotation mark&quot;&#34;
single quotation mark (apostrophe)&apos;&#39;
®registered trademark&reg;&#174;

Do comment if you have any doubts and suggestions on this HMTL escape code.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.