javascript - with - jquery selector wildcard




jQuery selector regular expressions (7)

Add a jQuery function,

(function($){
    $.fn.regex = function(pattern, fn, fn_a){
        var fn = fn || $.fn.text;
        return this.filter(function() {
            return pattern.test(fn.apply($(this), fn_a));
        });
    };
})(jQuery);

Then,

$('span').regex(/Sent/)

will select all span elements with text matches /Sent/.

$('span').regex(/tooltip.year/, $.fn.attr, ['class'])

will select all span elements with their classes match /tooltip.year/.

I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.

I have looked for this myself but have been unable to find information on the syntax and how to use it. Does anyone know where the documentation for the syntax is?

EDIT: The attribute filters allow you to select based on patterns of an attribute value.


I'm just giving my real time example:

In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".

document.querySelectorAll("[id^='select2-qownerName_select-result']");

When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.

$("[id^='select2-qownerName_select-result']")


If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ jquery selector

For example if your want to only select div with id starting with "abc", you can use $("div[id^='abc']")

A lot of very useful selectors to avoid use of regex can be find here : http://api.jquery.com/category/selectors/attribute-selectors/


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.


You can use the filter function to apply more complicated regex matching. Here's an example which would just match the first three divs (live demo here):

<div id="abcd"></div>
<div id="abccd"></div>
<div id="abcccd"></div>
<div id="abd"></div>
$('div')
    .filter(function() {
        return this.id.match(/abc+d/);
    })
    .html("Matched!");


var test = $('#id').attr('value').match(/[^a-z0-9 ]+/);

Here you go!





jquery-selectors