Josh
Josh

Reputation: 12566

jQuery Regex Question - Simple Match

How can I match something using jquery that is set up as such:

I want to do something like:

$("div:regex(id, intersection_*_*_5)").each(function(){
    $(this).click();
});

Is this doable? Assuming, the * is a wildcard, which I cannot seem to get to work.

Upvotes: 1

Views: 550

Answers (4)

user113716
user113716

Reputation: 322612

If you don't want a plugin, and you don't want to create your own selector filter, do this:

$("div[id^=intersection]").filter(function() {
    var header = this.id.substr(13); 
    var regex = new RegExp('_[a-zA-Z]+_\\d+_' + header + '$');
    return regex.test(this.id);
}).click();

It would be best if your <div> elements had a class in order to improve performance.

Something like:

$("div.intersection[id^=intersection]")...

Upvotes: 2

CaffGeek
CaffGeek

Reputation: 22064

With filter, and a proper regex, this should work

$("div:regex(id, ^intersection_\d_\d_5$)").each(function(){
    $(this).click();
});

EDIT:

Try this regex instead ^intersection_[\w-[0-9]]+_\d+_\d+$

You can replace parts between two underscores with the specific word/number if you know what it is.

Upvotes: 2

Marcis
Marcis

Reputation: 4617

Use filter method with custom function. Something like this:

var r = new RegExp("intersection_\d+_\d+_"+num);
$("div").filter(function(){
  return $(this).attr("id").match(r);
}).click();

Upvotes: 0

Whit
Whit

Reputation: 1159

There is regex selector for jQuery:

http://james.padolsey.com/javascript/regex-selector-for-jquery/

That is used like this:

$(':regex(id,^[aeiou])');

Upvotes: 0

Related Questions