user3729249
user3729249

Reputation: 31

RegExp uncaught TypeError: Cannot read property '1' of null

I found this code;

navigator.appVersion.match(/MSIE ([\d.]+)/)[1];

For detecting browser version. This code works in IE 8 below but not on google chrome. The error in google chrome says;

Uncaught TypeError: Cannot read property '1' of null

and it points to the line where this code belongs;

navigator.appVersion.match(/MSIE ([\d.]+)/)[1];

Any idea how to fix this issue?


just to make things clear what i'm trying to accomplish here is to detect the browser version:

var version = navigator.appVersion.match(/MSIE ([\d.]+)/)[1];

if(version <= 8.0)

{
   execute code;
}

Everything works fine in IE but I got an error in google chrome which is:

Uncaught TypeError: Cannot read property '1' of null

and it points to the line where this code belongs;

navigator.appVersion.match(/MSIE ([\d.]+)/)[1];

Upvotes: 3

Views: 4099

Answers (1)

Alex
Alex

Reputation: 11245

match can return null if regexp don't find anything. So you must first get matches and check have you any match or not. Try this:

var ieMatches = navigator.appVersion.match(/MSIE ([\d.]+)/);
var isIE = !!ieMatches[1];

Upvotes: 3

Related Questions