Mihai Bujanca
Mihai Bujanca

Reputation: 4217

Check if id matches pattern

I'm no regex geek, and I've been searching for a while but I don't really know how to do this: I need to get all the inputs with an id that looks like mywordsomenumber. For example match all inputs with id keyword1 keyword2 etc.

I tried

a=$("[id^=tokenfield(\d+)]");
a=$("[id^=tokenfield(0-9)]");

and some others, but I don't really have a good understanding of regex, and it seems like I can't get to the bottom of it

Can anyone help, please? Thanks

Upvotes: 0

Views: 2142

Answers (2)

LeGEC
LeGEC

Reputation: 51990

jQuery's Atribute starts with selector does not support regexes, it only works with exact strings.

You can select the nodes starting with "tokenfield", then do the extra check in javascript :

$('[id^="tokenfield"]').filter(function(){
    // extract the remaining part :
    var tail = this.id.slice(10); // 10 == "tokenfield".length
    // run it through parseInt :
    var number = parseInt(tail, 10);

    // isNaN will tell you if the parseInt failed :
    var isNumber = !isNaN(number);

    return isNumber;
});

However, as stated in the docs :

This selector can be useful for identifying elements in pages produced by server-side frameworks that produce HTML with systematic element IDs. However it will be slower than using a class selector so leverage classes, if you can, to group like elements.

If you have control over the code which generates the html, you would be better off generating nodes with the following structure :

<div class="tokenfield" data-token="123"></div>
<div class="tokenfield" data-token="456"></div>
<div class="tokenfield" data-token="789"></div>

Usage example :

$('.tokenfield').each(function(){
    var number = $(this).attr('data-token');
    // do something ...
 });

Upvotes: 0

itsananderson
itsananderson

Reputation: 793

I don't think you can use a RegEx to match attributes. [id^=tokenfield] matches attributes that begin with the exact string 'tokenfield'. It's a "starts with" match, not a "regex match".

You could use a manual filter.

Here's a JSFiddle: http://jsfiddle.net/itsananderson/U233z/

Basically you find all elements that begin with the fixed text ("item" in the example), and then filter based on an actual regex match for ids that end with a number.

var a = $('[id^=item]').filter(function() {
    return $(this).attr('id').match(/item[0-9]+/); 
});

Edit: Just noticed someone already gave a similar answer in the comments. Regardless, hopefully this is useful to someone

Upvotes: 3

Related Questions