Javascript regex not working in IE
So I've got this table being generated and each cell is given a unique id which is r#c# where the # is the row/column. I've got the code below that extracts the row number and column number from the ID 开发者_开发百科of the cell on mouseover, and it works just fine in firefox and chrome, but does not work in internet explorer.
var cell_id = $(this).attr("id");
var matches = /[a-z]+(\d+)[a-z]+(\d+)/(cell_id);
var row = matches[1];
var col = matches[2];
Why doesn't this work in explorer?
In Internet Explorer, a regex cannot be used as a function. The equivalent is the exec()
method, which is implemented cross browser.
var matches = /[a-z]+(\d+)[a-z]+(\d+)/.exec(cell_id);
Felt that this answer was a little incomplete without mentioning that Internet Explorer isn't the only browser that doesn't allow a regular expression to be executed like a function. In fact, it's a Mozilla extension and it's not even defined in the ECMAScript 3rd or 5th editions. You can easily check to see if it's supported using the
typeof
operator:
if (typeof / / == "function")
// Regex can be used like a function
else if (typeof / / == "object")
// Regex cannot be used like a function
I don't really understand why this was even implemented or why you'd even want to check for it, it's best to just err on the side of caution and use the exec method.
精彩评论