I am loading a text file like this...
Cue Target Info Group
CONTACTS FRIENDS genuine Group1
EXECUTIVE PRODUCER genuine Group1
via jQuery with this function...
var stimuliArray = "";
jQuery.get("Words1.txt", function(data){
stimuliArray = data.split("\n")
});
This works fine to split the tab-delimited file by each new line...
Cue Target Info Group,CONTACTS FRIENDS genuine Group1,EXECUTIVE PRODUCER genuine Group1
Now I can also modify it to split by tab...
var stimuliArray = "";
jQuery.get("Words1.txt", function(data){
stimuliArray = data.split("\t")
});
And it will give this result...
Cue,Target,Info,Group CONTACTS,FRIENDS,genuine,Group1
EXECUTIVE,PRODUCER,genuine,Group1
I want the output to be like my original file...
Cue Target Info Group
CONTACTS FRIENDS genuine Group1
EXECUTIVE PRODUCER genuine Group1
...so that I can access data like this (e.g., array[2][1]) and the output would be....
PRODUCER
I have tried to add a line of code to split by tab or new lines AFTER the jQuery function but it does not work at all...
stimuliArray = stimuliArray.split("\t");
The array remains unchanged with that kind of code.
I just want the file to be accessible like a normal array so that I can access information line-by-line and in whatever index I choose. Thanks for any hints!
You need to split the text by lines (\n
) and then each line by tab (\t
). Something like this.
stimuliArray = data.split('\n').map(function(ln){
return ln.split('\t');
});
First a step by step:
var source = `Cue Target Info Group
CONTACTS FRIENDS genuine Group1
EXECUTIVE PRODUCER genuine Group1`;
// split the source by line first
var lines = source.split('\n'); // lines is now an array where each element is one line of text
// Now loop through each line and split the line by tab
// by applying a map function to each line
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
var output = lines.map(function(line) {
return line.split('\t'); // returns a new array of words (for each line);
});
console.log(output[2][1]); // displays PRODUCER
If you fancy unreadable code or ES6, here is a 1 liner:
var source = `Cue Target Info Group
CONTACTS FRIENDS genuine Group1
EXECUTIVE PRODUCER genuine Group1`;
var output = source.split('\n').map(line => line.split('\t'));
console.log(output[2][1]); // displays PRODUCER
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