Home > Net >  How to put contents of a file into an array using vanilla Javascript?
How to put contents of a file into an array using vanilla Javascript?

Time:11-05

I would like to know if there is a possibility to get the text content of a file and transform it in a string or array, so that I can get random words from it.

I have to solve the following coding challenge in Javascript:

**

A program that randomly displays words from a text.

1.) Read a text file with a lot of content and randomly output a certain number of words

Example:

*enter how many words you want: 5

Output: anything acceptance shall and EVEN*

**

I manage to write a code that displays a text on the page, but I can't think of a solution to get the content and get random words from it.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Random Tweet Generator</title>
    
    <input type="file" name="inputfile" id="inputfile">
    <br>
   
    <pre id="output"></pre>
    
    <style>
     
    </style>
  </head>
  <body>
    <h1>Random Tweet Generator</h1>
    <script>
        document.getElementById('inputfile')
        .addEventListener('change', function() {

        let fr=new FileReader();
        fr.onload=function(){
        document.getElementById('output')
        .textContent=fr.result;
        }

        fr.readAsText(this.files[0]);
        })
    </script>
  </body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

  1. You can prompt the user for a number.

  2. You can run a regex match on the returned text that looks for words. This will return an array.

  3. You can then use a loop from zero to the prompted number, splicing out random word from the array and logging it. Note that splice returns an array so you need to access the first element.

const output = document.getElementById('output');
const input = document.getElementById('inputfile');
input.addEventListener('change', handleChange, false);

const numberOfWords =  prompt('How many words?');

function randomNumber(max) {
  return Math.floor(Math.random() * (max - 0)   0);
}

function handleChange() {

  // The regex to match words
  const regex = /\w(?<!\d)[\w'-]*/g;
  let fr = new FileReader();
  fr.onload = function () {

    // Produce an array of words in the file
    const arr = fr.result.match(regex);

    // From 0 to the numberOfWords
    // get a random number based on the length of the array
    // splice a word out and log it
    for (let i = 0; i < numberOfWords; i  ) {
      const rnd = randomNumber(arr.length);
      const word = arr.splice(rnd, 1);
      console.log(word[0].toLowerCase());
    }
  }
  fr.readAsText(this.files[0]);
}
<input type="file" name="inputfile" id="inputfile">
<br>
<pre id="output"></pre>
<h1>Random Tweet Generator</h1>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Assuming you are reading a text file, then

fr.onload=function()
{
 let text  = fr.result;
 let lines = text.split("\r\n");       
}

will split the file into lines. Now you could randomly pick a line from the file by

let randomline = lines[Math.floor((Math.random() * lines.length))];

But of course, how you "cut" the files into pieces is up to you. Want to split by, say, spaces?

let words      = text.split(" ");
let randomword = words[Math.floor((Math.random() * words.length))];

Long story short, there's no definite answer to your question, but here are some hints on how to move on.

  • Related