views:

221

answers:

2

I have a bunch of elements with names similar to "comp[1].Field" or "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

A: 

It looks pretty good to me!

nickf
+1  A: 

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 */ }
ithcy
Great catch. Thanks
sdr
Another issue: If $(":input:last") doesn't select anything, then .attr("name") will be undefined and .match will error out.
sdr
Also true... awareness is raised :)
ithcy