简体   繁体   中英

Search/Filter Javascript Array which was created from a text file

I hope someone have an idea or could give me some input on my problem.

Starting scenario: A .txt Logfile is created by a software and I try to create a website query which shows contained error messages from that log clearly arranged among each other.

So far I have the code to read the file as a variable, map the content as an array and split it to single lines.

<html>
<div>
Select Errorlog:
<input type="file" id="fileInput">
</div>

<pre id="displayFile"></pre>
<script>

   var fileInput = document.getElementById('fileInput');

   fileInput.addEventListener('change', function(e) {

          var file = fileInput.files[0];
          var reader = new FileReader();

   reader.onload = function(e) {

          var dateiinhalt = reader.result;
          var arr = dateiinhalt.split("\n");

   document.getElementById("Errorlog").innerHTML = arr[1];

};
 reader.readAsText(file);           
});
</script>
<p id="Errorlog"></p>
</html>

That was the easy job, but now I'm desperate to filter the array or to display certain index values of the array.

The Logfile itself looks like

2020-02-26 00:00:00 | ERROR | Message
2020-02-26 00:00:01 | INFO | NewEvent
2020-02-26 00:00:01 | ERROR | Message 2

The goal is to show every line which contains "ERROR" at once. I tried several filter/search functions, but everything I tried did not work (fe array.prototype.filter or indexOf).

Assuming that after the .split() you have an array of log lines as strings, a simple way to filter it for errors would be:

var arr = dateiinhalt.split("\n");
arr = arr.filter(line => line.indexOf("ERROR") >= 0);

or, in a more old-fashioned style:

arr = arr.filter(function(line) { return line.indexOf("ERROR") >= 0; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM