I have a bunch of elements with names similar to "comp[1].Field" or 开发者_如何学JAVA"comp[3].AnotherField" where the index (1 or 3) changes. I'm trying to extract the index from the name.
Right now I'm using:
var index = $(":input:last").attr("name").match(/\[(\d+)\]/)[1];
but I don't feel like this is the best way to do this.
Any suggestions?
Thanks
What you have is actually a pretty good way to do it, but you should add some checking that ensures that match() actually returns an array (meaning the string was found) and not null, otherwise you'll get a type error.
example:
var index = $(":input:last").attr("name").match(/\[(\d+)\]/);
if (match) { index = match[1]; }
else { /* no match */ }
精彩评论