Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

javascript - How to parse Text File to Array line by line?

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">
question from:https://stackoverflow.com/questions/65927801/how-to-parse-text-file-to-array-line-by-line

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use split(" ") 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("
");
      console.log(lines);
    };
    reader.readAsText(input.files[0]);
  },
  false
);
<input type="file">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...