Jquery Selector Regular Expressions

jQuery selector regular expressions

James Padolsey created a wonderful filter that allows regex to be used for selection.

Say you have the following div:

<div class="asdf">

Padolsey's :regex filter can select it like so:

$("div:regex(class, .*sd.*)")

Also, check the official documentation on selectors.

UPDATE: : syntax Deprecation JQuery 3.0

Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:

jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
return function (elem) {
var matchParams = expression.split(','),
validLabels = /^(data|css):/,
attr = {
method: matchParams[0].match(validLabels) ?
matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels, '')
},
regexFlags = 'ig',
regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
});

Regex in Jquery Selectors

There exists a regex filter to elements selectors that you need to append to jquery:

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

You can then use it as below:

// Select all elements with an ID starting a vowel:
$(':regex(id,^[aeiou])');

// Select all DIVs with classes that contain numbers:
$('div:regex(class,[0-9])');

// Select all SCRIPT tags with a SRC containing jQuery:
$('script:regex(src,jQuery)');

In your case the following shall match:

 $(':regex(id,\w*-1)');

Or you can use filter with just jquery:

$('*').filter(function() {
return this.id.match(/\w*-1/);
}).click(function(){ //your click event code here });

How can I select an element by ID with jQuery using regex?

You can combine both selectors in a multiple attribute selector.

​$("[id^=AAA_][id$=_BBB]")

It will return all the elements that matches all the specified attribute filters:

  • [id^=AAA_] matches elements with id attribute starting with AAA_, and
  • [id$=_BBB] matches elements with id attribute ending with _BBB.

Another generic alternatives:

  • Using a custom :regex() selector,
  • Using a .filter()-based approach.

Using Regex in :contains jQuery Selector

You cannot use a regular expression using the :contains() selector.

According to the documentation, nowhere does it say a regex can be used, and the parameter text is just a plain string text:

text: A string of text to look for. It's case sensitive.

What you're looking for is using the filter's function parameter:

screenshot of function signature in documentation

This allows you to write custom code in the function (which can include a regular expression), and return true for elements that match the expression.

For more information, see "Using a Filter Function" section in the linked documentation.

Pass Regex To JQuery Selector

You can use starts with and ends with attribute-value selector

$('[id^="prefix_"][id$="_postfix"]')

This will select all the elements whose id starts with prefix_ and ends with _postfix.


If the page contains many elements whose id starts with prefix_ and ends with _postfix but doesn't match the criteria that in between them should be one or two numbers, ex. <div id="prefix_tushar_postfix"></div>, the starts with and ends with selector will not work. In this case filter can be used in combination with attribute selectors.

Demo

var regex = /^prefix_\d{1,2}_postfix$/;

// Narrow down elements by using attribute starts with and ends with selector

$('[id^="prefix_"][id$="_postfix"]').filter(function() {



// filter the elements that passes the regex pattern

return regex.test($(this).attr('id'));

}).css('color', 'green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="prefix_1_postfix">prefix_1_postfix</div>

<div id="prefix_123_postfix">prefix_123_postfix</div>

<div id="prefix_tushar_postfix">prefix_tushar_postfix</div>

<div id="prefix__postfix">prefix__postfix</div>

<div id="prefix_11_postfix">prefix_11_postfix</div>

<div id="prefix_aa_postfix">prefix_aa_postfix</div>

jQuery selector with RegEx not accepting expressions

Selectors don't test regular expressions, but you don't need it here. There's an "attribute starts with" selector, attr^=string.

console.log($('div[aria-label^="FromTo #"]').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div aria-label="FromTo #abc124">Accept</div>
<div aria-label="FromTo #dd_13">Accept</div>
<div aria-label="FromTo #_bd33">Accept</div>
<div aria-label="FromTo #kld9L">Accept</div>
<div area-label="something else">Not accept</div>
<div>Not ARIA</div>

Find all elements based on ids using regex on jQuery selector

If you were doing this with regex, the expression would simply be:

item-\d-top

Where the \d indicates any single digit (0..9), and the other characters have no special meaning (so are treated as literals).

However, jQuery doesn't currently have a regex filter (only things like start/end/contains/etc) - so you would have to create your own one (which is possible, but if you were considering that you should stop and consider what/why you're filtering and figure out if there's a better way first).

Much simpler would be to create a class (as serg555 suggests), since that's exactly how you're treating these items.

Or (if you can't change the markup to add the class) then use the existing filters, expanding on g.d.d.c's answer, I might do:

$('div[id^=item-][id$=-top]').hide()

(Since you may have multiple items ending with just 'top', either now or in future, so you need to be more specific to avoid unintentionally hiding other things.)

regular expression in jQuery selectors

Regular expressions aren't needed here. Just use :has and attribute selectors:

$(".questionItem:has(input[name$='.SetAnswer'][value='?'])");

Fiddle: http://jsfiddle.net/jonathansampson/S8kft/



Related Topics



Leave a reply



Submit