Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i convert a .txt document into an array in JavaScript?

I am trying to convert a .txt deocument into an array.

The document has names in it and is structured like this:

Name1
Name2
Name3

The program has to read the lines and the output should be

["Name1","Name2","Name3"].

I have looked all over the internet, but most solutions just involve node.js, which i cannot install on the computer I need the software on, or some complex xmlhttp code I do not understand. I am just looking for a simple solution.

Can anybody help?

like image 728
PhDaher Avatar asked Oct 20 '25 16:10

PhDaher


1 Answers

To fetch the file contents you can use the fetch API in js which is pretty simple ( just pass the file url inside as parameter ) and clean to use .. Moreover to solve your issue regarding converting the text extracted from the file into an array you can use string.split method !

async function getFile(fileURL){
    let fileContent = await fetch(fileURL);
    fileContent = await  fileContent.text();
    return fileContent;
}

// Passing file url 
getFile('file.txt').then(content =>{
   // Using split method and passing "\n" as parameter for splitting
   let array =  content.trim().split("\n");
   console.log(array);
}).catch(error =>{
    console.log(error);
});

After getting text you can use string.split method and when used with .trim() method will remove extra spaces too !

Read MDN docs for information about fetch API

like image 155
Sanmeet Avatar answered Oct 23 '25 07:10

Sanmeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!