Category: JavaScript

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.

Downloading A Zip File Using Javascript Is Not Rocket Science! Know how!

Initially, the prerequisite for downloading a simple text file in javascript requires FileSaver.js. This can be downloaded from here.

Next step would be the creation of zip file.

1. Download jSZip and load it in your html.

2. Here comes the core part where we initalize jSZip and download a zip file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 var zip = new JSZip();         

    //skip this step if you don't want your files in a folder.
    var folder = zip.folder("example");
    folder.file("myfile1.txt", "HELLO WORLD IN 1ST FILE"); //requires filesaver.js
    folder.file("myfile2.txt", "HELLO WORLD IN 2ND FILE");

    //...so on until you have completed adding files

    zip.generateAsync({type:"blob"})
               .then(function(content) {
                //see FileSaver.js
                saveAs(content, "example.zip");
      });