I'm reading a text file and converting it to JSON format using regex in my react project.It is working fine but not including last 20-30 lines of the text file. There is some problem while converting it to JSON but I am unable to understand the problem.
Here is my code:
readTextFile = file => {
let rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = () => {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status === 0) {
let allText = rawFile.responseText;
// console.log(allText)
let reg = /\d\d\d\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01]) (00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])/g;
let arr = [];
let start = null;
let line, lastSpacePos;
let match;
while ((match = reg.exec(allText)) != null) {
if(start) {
line = allText.slice(start, match.index).trim();
lastSpacePos = line.lastIndexOf(' ');
arr.push({
date: line.slice(0, 19),
text: line.slice(20, lastSpacePos).trim(),
user_id: line.slice(lastSpacePos).trim()
});
}
start = match.index
}
console.log(arr);
this.setState({
// text: JSON.stringify(arr)
text: allText
});
}
}
};