Reputation: 467
I'm filtering the text file in nodejs and the "match" regex is giving me error on the filtered array
var fs = require("fs");
var finalarray = [];
var data = [];
var data1 = [];
fs.readFile('dataforparsing', function (err, buf) {
finalarray = buf.toString();// convert the object into the string
data = finalarray.split("\n");// splitting based on new line
for (i = 0; i < data.length; i++) {
if (data[i].match(/sessionid:/g) && !data[i].match(/Input/g)) {// filtering of the rows
data1[i] = data[i].toString();
console.log(data1[i] + "\n");
}
}
var data3 = [];
for (i = 0; i < data1.length; i++) {
data3[i] = data1[i].match(/[0-9]{13}/g);
console.log(data3[i] + "\n");
}
});
The expectation is that the code should work in the last loop as well but it gives error at "data1[i].match(..)" and print the filtered output based on the REGEX expression.
Upvotes: 0
Views: 4093
Reputation: 623
Use Arrays's push method to set data1 array elements.
var fs = require("fs");
var finalarray = [];
var data = [];
var data1 = [];
fs.readFile('dataforparsing', function (err, buf) {
finalarray = buf.toString();// convert the object into the string
data = finalarray.split("\n");// splitting based on new line
for (i = 0; i < data.length; i++) {
if (data[i].match(/sessionid:/g) && !data[i].match(/Input/g)) {// filtering of the rows
data1.push(data[i].toString());
}
}
var data3 = [];
for (i = 0; i < data1.length; i++) {
data3[i] = data1[i].match(/[0-9]{13}/g);
console.log(data3[i] + "\n");
}
});
Hope this will help.
Upvotes: 1
Reputation: 207501
The problem is you only fill in indexes where you find matches
if (data[i].match .... ) { data1[i] = data[i].toString(); <-- that i is killing you }
so when you do not have a match you have
data[0] -- match
data[1] -- undefined
data[2] -- match
You want to use push() not set the index
data1.push(data[i]);
But in the end you are just rewriting filter()
var data1 = data.filter(item => item.match(/sessionid:/g) && !item.match(/Input/g))
Upvotes: 1