William Flinchbaugh
William Flinchbaugh

Reputation: 45

How can I read a text file as an array

I have a text file (not json) that looks like the following:

['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']

How can I read it and put into 2 arrays: ['a', 'b', 'c', 'd'] and ['e', 'f', 'g', 'h']?

I'm using this to read the file:

jQuery.get('filename.txt', function(data){
 alert(data);
});

Upvotes: 0

Views: 467

Answers (2)

ajai Jothi
ajai Jothi

Reputation: 2294

Solution 1:

  1. split the string by multiline(\r\n)
  2. loop through splitted array of string and replace the single-quote with double-quote to make it a valid JSON string
  3. parse JSON string with JSON.parse

const exampleData = `['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']`;

const multiLineTextToArray = (txt) => {
  return (txt.match(/[^\r\n]+/g) || []).map((line) => {
    // replace single quote with double quote to make it proper json string
    // then parse the string to json
    return JSON.parse(line.replace(/\'/g, '\"'));
  });  
};

/**
jQuery.get('filename.txt', function(data){
 alert(multiLineTextToArray(data));
});
*/

// example
console.log(multiLineTextToArray(exampleData));

Solution 2: constructing a valid JSON array

  1. replace multiline(\r\n) with ','
  2. replace single-quote with double-quote
  3. wrap the whole string with []
  4. parse the JSON string with JSON.parse

const exampleData = `['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']`;

const multiLineTextToArray = (txt) => {
  return JSON.parse(`[${txt.replace(/[\r\n]+/g, ',').replace(/\'/gm, '\"')}]`);
};

/**
jQuery.get('filename.txt', function(data){
 alert(multiLineTextToArray(data));
});
*/

// example
console.log(multiLineTextToArray(exampleData));

Upvotes: 1

user6057915
user6057915

Reputation:

my approach to this would be the following:

data contains all the information from the .txt file. So I would try to read the file line by line using split function like this.

var arrays = []; 

jQuery.get('filename.txt', function(data){

var splitted = data.split("\n"); // --> should return an array for each line 

// Loop through all lines 
for(var i = 0; i < splitted.length; i++) 
{

var line = splitted[i]; 

// Now you could remove [ and ] from string  
var removed = line.replace('[','').replace(']','');

// Now you can split all values by using , delimiter
var values = removed.split(',');  
 var array = []; // this will be a single array

// Now you can iterate through all values and add them to your array
for(var c = 0; c < values.length; c++) 
{

var value = values[c]; 

// Now you can add this value to your array
// this depends on the data structure you are using in JS 
// for example
array.push(value);  

}

// NOw all values are stored in first array so add it to the multi array
// this is an array in an array
arrays.push(array); 

}

});

Upvotes: 0

Related Questions