2

I need to load an array from a .txt file. It has few strings separated by commas (,).

So far I have found this.

That guy splits it with .split function but I have a problem. He uses an input to upload the file, however, I need to link the file to the HTML and than split it into an array and use it.

2 Answers 2

3

Just make sure the text file is accessible through an HTTP request on the same domain and you can read it fine. Here's an example where the text file is located in the webroot.

    $(function(){
        $.get('/whatever.txt', function(data){
            var array = data.split(',');
            console.log(array);
        });
    });
Sign up to request clarification or add additional context in comments.

5 Comments

I have all the files locally atm, and it doesn't. Both the html and the .txt file are in the same folder.
Did you remove the slash to use a relative path? Are you running a web server locally?
I am not running a web server locally and I did remove the slash.
That will not work with the given example. As stated you need to access the file via an HTTP request. I suggest you look at one of these threads. You could also upload the files to a web server for testing, but it's an unpractical way to work.
Perfect for my uses! I split a large newline separated data file, just using /\n/ instead of ','. Works perfectly!
1

You can read html files locally since html5. Check the html5 API and some examples here. Then use Alexanders answer to parse it.

EDIT: here and here are some good and short examples on how to use it.

4 Comments

Thanks for the answer. I have flew trough the docs but I couldn't find any code that would show how to link the .txt file into html, they were only showing how to use it.
The thing is that you need to use it together with a loading dialogue. So you just can't say var file = new File("foo.txt") but rather use a FileReader. I added some examples in my edit.
Oh...So I can't load it without having to upload it trough a button? I want it to download it in background, kind of like you link in .js files.
If you want to use Files locally in js you have to use this way I think. I was bummed about this as well when I wanted to use files in js for some students project... If you stumble upon a better way tell me please :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.