1

I have a text file filled with dictionary words that looks something like this:

banana
apple
orange
lemon
grape

and I want to be able to convert it to an array so that I can use it in a JavaScript file I am writing:

["banana", "apple", "orange", "lemon", "grape"]

For context, I'm making a request to the text file with the Fetch API. Does anyone know how I would be able to convert this?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
zsrobinson
  • 38
  • 4

2 Answers2

1

Your text is separated with line breaks \n. You can split into an array using split("/n"). In the event that there are spaces in your text, you should map that array through a trim() filter to remove the spaces.

let pre = document.querySelector('pre').innerHTML;
//without trimming
let arr = pre.split("\n");
console.log(arr)

//with trim
let trimmed = pre.split("\n").map(e=>e.trim());
console.log(trimmed)
<pre>
banana     
apple   
orange  
lemon
grape  
</pre>
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

These words are separated with enter (\n). You can just split it by \n and the array will create by itself. Here's the example:

let text = "banana\napple\norange\nlemon\ngrape"

let arr = text.split('\n')
console.log(arr)

Outut

[ 'banana', 'apple', 'orange', 'lemon', 'grape' ]

The evidence that words in files are separated by \n:

const fs = require('fs')

fs.readFile('words.txt', 'utf8' , (err, data) => {
    let arr = data.split('\n')
    console.log(arr)
})

words.txt should be the file with words you mentioned in the question.

blazej
  • 927
  • 4
  • 11
  • 21