Ad

Text File To Arraylist Javascript

- 1 answer

I have a txt file on mydomain.net/file.txt.How can I read this into an array filecontent where each new line is a element and ignore lines containing //? .

JavaScript

    var filecontent=[];
    function txtToArray(link){
    //code here
    }
    txtToArray("mydomain.net/file.txt");
document.write(filecontent);

mydomain.net/file.txt

//file.txt
    aaa
    aa1
    aa2
Ad

Answer

If you're in the browser, you'll have to fetch the file, parse the response as text, split the text into an array of lines, and filter the array for lines that do not start with //, then write the filtered array:

function filterAndWrite(text) {
    const arrayOfLines = text.split('\n');
    const startsWithDoubleSlash = new RegExp('^//');
    const filteredLines = arrayOfLines.filter((line) => !line.match(startsWithDoubleSlash));
    document.write(filteredLines);
}

function writeToDocument(link) {
    fetch(link)
        .then((response) => response.text())
        .then(filterAndWrite);
}

writeToDocument('mydomain.net/file.txt');
Ad
source: stackoverflow.com
Ad