How do you read/parse a text file line by line using html/javascript?

11,487

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).

Share:
11,487
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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.

    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

    • FlavorScape
      FlavorScape about 12 years
      please post a sample of the text file. Why are you not using json or XML?
  • A. Meshu
    A. Meshu about 5 years
    I know this is a really old answer, but i wonder if you can be kind and add sort of example/demonstration for the code..