12bio23
12bio23

Reputation: 203

Extracting specific Values from a text (txt) file using Java Script (JS)

I'm writing a webpage where you can upload text files and then do some analysis on the file.

the text file is formatted like this:

'*' is only used to make a list on stack-overflow not actually in the text file

I only need to extract the third column(three digits) and place the values in a variable that I can later use for my analysis.

How can I do this? I can't seem to find an answer with the javascript.

thanks

Upvotes: 0

Views: 1441

Answers (3)

Titus
Titus

Reputation: 22474

Here is a way of doing it:

document.querySelector('#fileInput').addEventListener('change', (e) => {
  readFile(e.target.files[0]);
});

function readFile(file) {
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = function() {
    const values = reader.result.split('\n').map(line => (+line.split(' ')[2]));
    console.log(values);
  };
}

const fileContent = `0 1 475
1 2 437
2 3 553
3 4 500
4 5 612
5 6 491
6 7 444
7 8 544
8 9 491
9 10 595`;

const blob = new Blob([fileContent], {type: 'text/plain'});
readFile(blob);
<input id="fileInput" type="file" onchange="readFile(this.files[0])">

In this example I've used a Blob to imitate a file but you can also use the <input type="file" /> to test the function with a real file.

What this does is to use a FileReader to read a file as text and then parse the content of the file by creating an array that has each line of text in the file as an element (reader.result.split('\n')) and then mapping that array to only keep the last number. That is achieved by splitting the line on every white space character and converting to a number and keeping only the third element from the resulting array (+line.split(' ')[2], the [2] selects the third element and + converts that element to a number).

Upvotes: 1

Alan Omar
Alan Omar

Reputation: 4217

You can use regular expression:

   let str= `0 1 475
1 2 437
2 3 553
3 4 500
4 5 612
5 6 491
6 7 444
7 8 544
8 9 491
9 10 595`

let re=/\d{3}$/gm

console.log(str.match(re))

Upvotes: 0

rb612
rb612

Reputation: 5563

You could do something like this, where the map function transforms each string into an integer:

const input = ["0 1 475",
               "1 2 437",
               "2 3 553",
               "3 4 500",
               "4 5 612",
               "5 6 491",
               "6 7 444",
               "7 8 544",
               "8 9 491",
               "9 10 595"];
const output = input.map((str) => parseInt(str.split(" ")[2]))
console.log(output);

Upvotes: 0

Related Questions