![](/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.