anon20010813
anon20010813

Reputation: 155

Return split string obtained from a multi line text file

I was trying to return data obtained from a text file by reading it and then popping everything after the comma. I tried to use split(',').pop() but this only works for 1 string. How can I make it iterate on every line in a text file then return the popped string. I included an example below. Any help is appreciated. Thanks in advance.

Example txt file:
orange,001
bannana,002
apples,003

would return:
001
002
003

//something like this but for everyline in the text file.
const reader = fs.readFileSync('filePath', 'utf-8');
const popped = reader.split(',').pop();
console.log(popped)

Upvotes: 1

Views: 664

Answers (2)

JustRaman
JustRaman

Reputation: 1161


const reader = fs.readFileSync('filePath', 'utf-8');
const lines = reader.split('\n');
lines.forEach((line)=>{
 const popped = line.split(',').pop();
 console.log(popped)
})

Upvotes: 2

Jamiec
Jamiec

Reputation: 136124

You would need to split by lines and then get every item after the , using map

const txt = `orange,001
bannana,002
apples,003`

const result = txt.split("\n").map(x => x.split(",")[1])
console.log(result);

Upvotes: 3

Related Questions