I'm trying to make a simple web application that allows me to upload a text file and display its contents in a tag. Also, when I press the "Parse" button, I need the text content to only keep all lines starting with "ACK" while maintaining its structure.
Here is my code:
// Javascript App.js
document.getElementById("openFile").addEventListener("change", function(){
var file = this.files[0];
var fr = new FileReader();
fr.onload = function(){
document.getElementById("fileContents").textContent = this.result;
}
fr.readAsText(file);
},false)
//error zone
document.getElementById("parse").addEventListener("click", function(){
document.getElementById("fileContents").textContent.startsWith("ACK") = this.result;
},false)
<!DOCTYPE html>
<html lang="pt-pt">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Parser</title>
</head>
<body>
<input type="file" id="openFile"/>
<button id="parse">Parse</button>
<br>
<br>
<br>
<!-- preformatted text -->
<pre id="fileContents"></pre>
<!--/preformatted text -->
<!-- app.js -->
<script src="js/app.js"></script>
</body>
</html>
答案 0 :(得分:1)
My only changes were to the event listener of the parse
button. I parsed the text of fileContents
so when clicking parse
the only lines left are the ones that begins with ACK
.
// Javascript App.js
document.getElementById("openFile").addEventListener("change", function(){
var file = this.files[0];
var fr = new FileReader();
fr.onload = function(){
document.getElementById("fileContents").textContent = this.result;
}
fr.readAsText(file);
},false)
document.getElementById("parse").addEventListener("click", function(){
let lines = document.getElementById("fileContents").textContent.split('\n');
lines = lines.filter((line)=>line.indexOf('ACK')===0);
let newPre = '';
lines.map((line)=>{newPre+=line + '\n';});
document.getElementById("fileContents").textContent = newPre;
},false)
<!DOCTYPE html>
<html lang="pt-pt">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Parser</title>
</head>
<body>
<input type="file" id="openFile"/>
<button id="parse">Parse</button>
<br>
<br>
<br>
<!-- preformatted text -->
<pre id="fileContents"></pre>
<!--/preformatted text -->
<!-- app.js -->
<script src="js/app.js"></script>
</body>
</html>