Simple regex to extract content between square brackets in jQuery

I have a bunch of elements with names similar to "comp [1] .Field" or "comp [3] .AnotherField" where the index changes (1 or 3). I am trying to extract an index from a name.

Now I am using:

var index = $(":input:last").attr("name").match(/\[(\d+)\]/)[1];

but I don’t feel that this is the best way to do this.

Any suggestions?

thank

+3
source share
1 answer

What you have is actually a pretty good way to do this, but you have to add some validation that ensures that match () actually returns an array (which means the string was found) and not null, otherwise you will get type of error.

Example:

var index = $(":input:last").attr("name").match(/\[(\d+)\]/);
if (match) { index = match[1]; }
else { /* no match */ }
+2

Source: https://habr.com/ru/post/1731288/


All Articles