0

I have problem with my script. I don't know how to put text into array line by line :((

Text File

Bob
Marc
Will
Tony

Output

Array[0:"Bob", 1:"Marc", 3:"Will", 3:"Tony"]

How I can achieve this output???

I tried something like this...

const input = document.querySelector('input[type="file"]');

input.addEventListener(
  "change",
  function(e) {
    const reader = new FileReader();
    reader.onload = function() {
      const lines = reader.result.split(" ");
      let array = [];
      for (var i = 0; i < lines.length; ++i) {
        array.push(lines[i]);
      }
      console.log(array);
    };
    reader.readAsText(input.files[0]);
  },
  false
);
<input type="file">

Do you have any ideas. Thanks.

5
  • what is the result of the example of what you tried above? Commented Jan 27, 2021 at 21:46
  • You can't have duplicate index 3 in an array. Commented Jan 27, 2021 at 21:47
  • are you using node ? Commented Jan 27, 2021 at 21:48
  • No, it's not Node. This is local javascript. Commented Jan 27, 2021 at 21:57
  • Result of code which I used look like this=> Array [0: "Bob, Marc, Will, Tony"] Commented Jan 27, 2021 at 21:58

1 Answer 1

1

Use split("\n") to use newline as the delimiter, not a space.

You don't have to copy the array with the for loop.

const input = document.querySelector('input[type="file"]');

input.addEventListener(
  "change",
  function(e) {
    const reader = new FileReader();
    reader.onload = function() {
      const lines = reader.result.split("\n");
      console.log(lines);
    };
    reader.readAsText(input.files[0]);
  },
  false
);
<input type="file">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.