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

268
Views
I am attempting to create a forEach method in order to get a substring of each array

I have a text file that looks like this: sciFi.png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, loft.png, basement.png, avenger.png, friend.png

I'm importing that file to a js doc and attempting to create an array out of that file and then use the forEach() method to create a substr() for each array element to take off the '.png' (so the output would be sciFi, posed, birdA, dolphin and so on).

Here is my code so far:

html

<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <title>My fabulous document</title>
</head>
<body>
  <div id="demo">
    <h2>The XMLHttpRequest Object</h2>
    <button type="button" onclick="loadDoc()">change content</button>
  </div>
</body>
<script type="text/javascript" src="getImgButton.js">
</script>
</html>

js

function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        pix = this.responseText;
        myPix = pix.split(",");      
        myPix.forEach(myFunction);
        function myFunction(myPix) {
         // var buttVal = myPix.substr(0,myPix.indexOf("."));
        }
      }
    };
    xhttp.open("GET", "imageList.txt", true);
    xhttp.send();
  }

I know I'm probably way off but I'm trying to figure out what to put in myFunction() to get this to work. Any suggestions?

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

0

Here's a modern way to write this:

async function loadDoc() {
  const response = await fetch('imageList.txt');
  const body = await response.text();
  const images = body.split(',').map(
    fileName => fileName.split('.')[0]
  );
  console.log(images);
}

The errors in your original snippet has to do with how you called forEach:

        const images = [];
        myPix.forEach(myFunction, function myFunction(item) {
          var buttVal = myPix.substr(0,myPix.indexOf("."));
          images.push(buttVal);
        });
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!