![](/img/trans.png)
[英]Read each line of a txt file by looking for the first word at the beginning of each line and delete the line of file
[英]How to read the first line of .txt file?
任何人都可以幫助如何閱讀.txt文件的第一行? 我有上傳example.txt的輸入類型文件,然后我想抓住該代碼的第一行。 我試過這樣的事情:
<input type="file" id="fileUpload" name="fileUpload"/> MyTest.txt //file name
function confirmFileSubmit(){
var fileName = $('#fileUpload').val();
alert($('#fileUpload').split('\n')[0]);
}
運行我的代碼后,這只是在警告框中輸出文件名。 我不確定如何閱讀文件的內容。 如果有人可以提供幫助,請告訴我。
你需要FileReader
function confirmFileSubmit(){
var input = document.getElementById('fileUpload'); // get the input
var file = input.files[0]; // assuming single file, no multiple
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result; // the entire file
var firstLine = text.split('\n').shift(); // first line
console.log(firstLine); // use the console for debugging
}
reader.readAsText(file, 'UTF-8'); // or whatever encoding you're using
// UTF-8 is default, so this argument
} // is not really needed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.