Home > front end >  Javascript array from txt and print it on local html
Javascript array from txt and print it on local html

Time:10-15

I have a problem with javascript code. I have to make local html which displays lines of text from .txt file. I found a code like this, which does it:

 <script>
 var fileInput = document.getElementById('inputfile');
 fileInput.addEventListener('change', function(e) {
     var file = fileInput.files[0];
     var reader = new FileReader();
     reader.onload = function(e) {
         document.getElementById('output').innerText = reader.result;
 };
     reader.readAsText(file);   
 });
 </script>

However, I need those to be displayed like in this code:

<script type="text/javascript">
    var arr = ['Heading 1','Para1','Heading 2','Para2','Heading 3','Para3'];
    var result = arr.map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
    document.getElementById('test').innerHTML = result ;
</script>

No matter how I try to combine this two, it doesnt seem to work (nothing gets displayed at all). I am rather green with regards to javascirpt, so could someone help me with that and, if possible, explain in rather simple language how is that supposed to be done?

.txt file would look something like:

Position1
description1 
position2 
description2 
pozition3 
...

CodePudding user response:

Your reader.result in the first example is a single multi-line string. For your second snippet to work, you need an array of strings, one-per-line.

Here's how you can split your multi-line text file in to an array of lines:

const txtFile = `Position1
description1 
position2 
description2 
pozition3`;

const lines = txtFile.split("\n");

console.log(lines);

Once you have these lines, you can proceed as you already showed. One warning: by using innerHTML you run in to the risk of injecting stuff in to your document you might not want. In most cases, it's better to construct the HTML elements in code and use innerText:

const txt = `Hello
This is a paragraph
Heading
Injected scripts! <img src=x one rror="console.log(1234)">`;

const lines = txt.split("\n");

// "Safe" approach: display contents as text
// This will _not_ log 1234
lines.forEach(
  (content, i) => {
    const el = document.createElement(i % 2 === 0 ? "h2" : "p");
    el.innerText = content;
    document.body.appendChild(el);
  }
);

// "Unsafe" approach: use innerHTML
// This _will_ log 1234
lines.forEach(
  (content, i) => {
    const tag = i % 2 === 0 ? "h2" : "p";
    document.body.innerHTML  = `<${tag}>${content}</${tag}>`
  }
)

  • Related