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>
<html>
<body>

  <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>
    </select>
  </div>

  <div class="half last"><textarea id="output" placeholder='Output...' spellcheck="false"></textarea></div>
  <script>
   
    // 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);
}
inputHandler();
methodToggleEl.onchange = inputEl.oninput = inputHandler;
</script>
</body>
</html>

Output:

HTML escape characters

Some Useful HTML Character Entities

ResultDescriptionEntity NameEntity Number
non-breaking space&nbsp;&#160;
<less than&lt;&#60;
>greater than&gt;&#62;
&ampersand&amp;&#38;
double quotation mark&quot;&#34;
single quotation mark (apostrophe)&apos;&#39;
¢cent&cent;&#162;
£pound&pound;&#163;
¥yen&yen;&#165;
euro&euro;&#8364;
©copyright&copy;&#169;
®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.