Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could create an <input type="file"> for opening a file from your computer, read it with a FileReader and split() the result by newline (with for example regex /\r?\n/) to become an array of words.

const openFile = (e) => {
  const reader = new FileReader(); // filereader
  reader.readAsText(e.target.files[0]); // read as text
  reader.onload = () => {
    const text = reader.result;
    const result = text.split(/\r?\n/); // split on every new line
    console.log(result); // do something with array
  };
};
<input type='file' accept='text/plain' onchange='openFile(event)'>

You can try it out in this fiddle.

You could also accomplish this in another (newer) way as suggested in the comments, using .then.

const openFile = (e) => {
  e.target.files[0].text().then((t) => {
    const outcome = t.split(/\r?\n/);
    console.log(outcome);
  });
};
<input type='file' accept='text/plain' onchange='openFile(event)'>

about 4 years ago · Juan Pablo Isaza Relatório

0

Since you won't use node, I am assuming you're running your code on a browser. And the file from an <input type="file"/>

<html>
  <input type="file" id="inputFile">

  <script>
   const inputFile = document.querySelector('#inputFile');

   inputFile.addEventListener('change', () => {
     const fileReader = new FileReader();
     fileReader.onload = e => {
       const array = e.target.result.split('\n');
       console.log(array);
     };
     fileReader.readAsText(inputFile.files[0], 'UTF-8');
   });
  </script>
</html>
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda