HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Escape or unescape HTML using JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptunescapeescapeusinghtml

Problem

Escaping and unescaping HTML is an unavoidable part of web development. In essence, all you have to do to convert text into an HTML-safe string is to replace the characters that have special meaning in HTML with their respective HTML entities. The reverse operation is to replace the HTML entities with their respective characters.
Here's a table of the characters that need to be escaped and their respective HTML entities:
| Character | HTML Entity |
| --------- | ----------- |
| & | & |

Solution

const escapeHTML = str =>
  str.replace(
    /[&<>'"]/g,
    tag =>
      ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        "'": '&#39;',
        '"': '&quot;'
      }[tag] || tag)
  );

escapeHTML('<a href="#">Me & you</a>');
// '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'


| Character | HTML Entity |
| --------- | ----------- |
| & | &amp; |
| < | &lt; |
| > | &gt; |
| ' | &#39; |

Code Snippets

const escapeHTML = str =>
  str.replace(
    /[&<>'"]/g,
    tag =>
      ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        "'": '&#39;',
        '"': '&quot;'
      }[tag] || tag)
  );

escapeHTML('<a href="#">Me & you</a>');
// '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
const unescapeHTML = str =>
  str.replace(
    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
    tag =>
      ({
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&#39;': "'",
        '&quot;': '"'
      }[tag] || tag)
  );

unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;');
// '<a href="#">Me & you</a>'

Context

From 30-seconds-of-code: escape-unescape-html

Revisions (0)

No revisions yet.