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?
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.splitmethod and when used with.trim()method will remove extra spaces too !
Read MDN docs for information about fetch API
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With