如何使用 html/javascript 逐行读取/解析文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9917246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you read/parse a text file line by line using html/javascript?
提问by CharlesTWall3
I am trying to parse a text file that contains a bunch of test questions/answers to code a multiple choice test taker.
我正在尝试解析一个包含一堆测试问题/答案的文本文件,以编写多项选择测试者的代码。
The questions and answers are all on separate lines so I need to read each file line by line and somehow parse it by just using html/javascript/jquery.
问题和答案都在单独的行上,所以我需要逐行读取每个文件,并以某种方式仅使用 html/javascript/jquery 来解析它。
How would I do this? THANKS!
我该怎么做?谢谢!
The text file has the extension .dat but is actually a text file. Its just the format these come in and there are too many to change... http://www.mediafire.com/?17bggsa47u4ukmx
文本文件的扩展名为 .dat,但实际上是一个文本文件。它只是这些进来的格式,有太多要改变的...... http://www.mediafire.com/?17bggsa47u4ukmx
回答by CharlesTWall3
try this
试试这个
function readQAfile(filename){
$.ajax(filename,
{
success: function(file){
var lines = file.split('\n');
var questions = [];
var length = lines.length;
for(var i = 0; i < length; i+=2){
questions.push({
question: lines[i],
answer: lines[i+1] || "no answer"
})
}
window.questions = questions;
}
}
);
}
to use this you'll need to be running the website on a server (a local server is fine).
要使用它,您需要在服务器上运行网站(本地服务器很好)。
回答by Peter Aron Zentai
To get started try using regexp.
要开始尝试使用正则表达式。
The following expression will split your text on every $$[number] occasion. From there you can brute force slice and cut and chop your string further.
以下表达式将在每个 $$[number] 场合拆分您的文本。从那里你可以蛮力切片并进一步切割和切碎你的字符串。
Example code:
示例代码:
var regex = /($$\d+)/g;
var str = "adasda$adadad$adsads\nadad\nadad$";
console.log(str.split(regex));
["", "$$1", "adad sad", "$$23", "asdad", "$$3", ""]
["", "$$1", "adad sad", "$$23", "asdad", "$$3", ""]