Escape HTML entities in JavaScript variables to render as plain text

Rendering strings containing HTML entities would require special attention as browser can only understand HTML tags and are formatted according to the HTML entities. So this post will help in dealing with such cases which will render HTML entities as plain text in browser.

First step:

1
2
3
4
5
function escapeHtml (string) {
return String(string).replace(/[&<>”‘`=/]/g, function (s) {
return entityMap[s];
});
}

This is the major function that does the espcaping of HTML entities. As you can see it require an entityMap which contains all HTML entities that you want to require.

So here is our enitityMap:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var entityMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;',
        '/': '&#x2F;',
        '`': '&#x60;',
        '=': '&#x3D;'
};

As you can notice that these are the possible basic HTML entities, you can convert them to escape string that browser understands as plain text.

So what next:

We are all ready and I am giving you a sample text to test this.

1
2
text = escapeHtml(text);
$("#demo").html(text);

When you do all the above mentioned steps correctly, you would get the following result.

1
<स्क्रिप्ट भाषा = PHP> </ script> </ Body> # यह एक टिप्पणी है, और print <<<END $ 4 <tab> = <tab2 <tab> + <tab> 2// रिक्त स्थान और टैब <? Php ?>

Observe that all HTML tags are restored as it is.

Still having a problem you can check our live demo over here.

One comment

Join the Conversation

Your email address will not be published.