开发者

Simple regex to extract contents between square brackets in jQuery

开发者 https://www.devze.com 2022-12-19 06:31 出处:网络
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.

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 */ }
0

精彩评论

暂无评论...
验证码 换一张
取 消