Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
javascript printing array into paragraphs

I am trying to make a local html to display some text from txt file (also local). I used this to read file into array and print it:

<input type="file" name="files" id="inputfile">
<script type="text/javascript"> 
document.getElementById('inputfile')
.addEventListener('change', function() {
    var test=new FileReader();
    test.onload=function(){
        document.getElementById('output')
                .textContent=fl.result;
    }
    test.readAsText(this.files[0]);
})
</script>

However, I would like to print it from the array into paragraphs, line by line (first line goes into heading, second into paragraph, third into heading and so on...). Is there a way to do it automaticaly from an array, or would I have to do it by hand for each one? I am kinda green in javascript so I would rather refrain from using node etc.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

If the headers and paragraphs are always strictly alternating, you can check whether each array index is odd or even to decide whether to wrap it in header or paragraph tags. One way:

arr = ["header", "paragraph", "header", "paragraph", "header", "paragraph"]

joined = arr.map((el, i) => {
  return (i % 2 === 0) ? `<h1>${el}</h1>` : `<p>${el}</p>` ;
}).join('')

console.log(joined)
  

about 4 years ago · Juan Pablo Isaza Report

0

const arr = ['Heading 1','Para1','Heading 2','Para2','Heading 3','Para3'];

const result = arr.map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
document.getElementById('output').innerHTML = result ;
<div id="output"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Put this in your code:

function arrToPar(arr){ //For JS-Array --> HTML content
    var out = "";
    for(var i = 0; i < arr.length; i++){
        out += arr[i] + "<br>";
    }
    return(out);
}

Or...

function arrToString(arr,joiner = " "){ //For JS-Array --> JS-String
    var out = ""; //The parameter "joiner", by default, is a space
    //This means that you only need to specify "arr", but you can do
    //a second parameter. This function behaves like arr.join(joiner).
    for(var i = 0; i < arr.length; i++){
        out += arr[i] + joiner;
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!