Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting text file by newlines and tab in JavaScript

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!

like image 968
Kalif Vaughn Avatar asked Dec 18 '17 21:12

Kalif Vaughn


2 Answers

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');
});
like image 159
Alex Kudryashev Avatar answered Sep 25 '22 01:09

Alex Kudryashev


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
like image 35
Sébastien Avatar answered Sep 26 '22 01:09

Sébastien