Question

I have a routine that produces id attributes on a tag -- anywhere from [1] to [??]

I want to be able to evaluate the string and extract the id ordinal using jquery.

Here is my sample markup:

<div id="abc[1]"></div>
<div id="abc[15]"></div>

I know I can do something like this:

var n1=???.indexOf("[");
var n2=???.indexOf("]");
var theID = $('#???').substr(n1,n2);

But I am wondering how to make it work as simply as possible.

I want theID to retrieve 1 or 15, etc.

Was it helpful?

Solution

Try String.replace()

var n = $(el).attr('id');
var theID = n.replace('abc[', '').replace(']', '');

OTHER TIPS

You can do it with native js regexes.

var n=jQuery(element).attr('id');
var bracketedarray=n.match(/\[\d+\]/g);
// will return, for example [["15"]]
var thenumber=bracketedarray[0].replace(/\[|\]/g,'');
// will return, "15"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top