문제

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.

도움이 되었습니까?

해결책

Try String.replace()

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

다른 팁

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"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top