Reputation: 419
My task is to find some information in a log file using regular expressions in javascript. I cannot find the problem with my code. I am keep getting an error: Uncaught TypeError: Cannot read property '1' of null
Log file example:
202.32.92.47 - - [01/Jun/1995:00:00:59 -0600] "GET /~scottp/publish.html" 200 271
ix-or7-27.ix.netcom.com - - [01/Jun/1995:00:02:51 -0600] "GET /~ladd/ostriches.html" 200 205908
ram0.huji.ac.il - - [01/Jun/1995:00:05:44 -0600] "GET /~scottp/publish.html" 200 271
And with the following code I am trying to get the name of hosts:
var hostName = /(.*)\s\-\s\-/g;
$(".file").change(function(){
var file = "log";
$.get(file,function(data){
var lines = data.split("\n");
var len = lines.length;
//var arrayOfDomains = [];
//var match = [];
for(i=0;i<3;i++){
$("#123").append("<p>"+hostName.exec(lines[i])[1]+"</p><br>");
}
});
});
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" class="file">
<script type="text/javascript" src="func.js"></script>
<div id="123"></div>
</body>
</html>
I think nothing is wrong with my regular expression as I it with some lines with it individually and it worked fine. The code only stops working when using loop to go through lines in array of lines.
Upvotes: 0
Views: 48
Reputation: 187
It is breaking on this line
$("#123").append("<p>"+hostName.exec(lines[i])[1]+"</p><br>");
because .exec() is sometimes returning null
due to your regex being global.
I found this question which should be able to help you fix your problem. RegExp.exec() returns NULL sporadically
From that question I would propose it is as easy as moving the hoseName regex assignment inside the loop like this:
$(".file").change(function(){
var file = "log";
$.get(file,function(data){
var hostName = /(.*)\s\-\s\-/g; //Placed here
var lines = data.split("\n");
var len = lines.length;
//var arrayOfDomains = [];
//var match = [];
for(i=0;i<3;i++){
$("#123").append("<p>"+hostName.exec(lines[i])[1]+"</p><br>");
}
});
});
Upvotes: 1