Search code examples
regexsizzle

Can a sizzle selector evaluate a regular expression?


I need to select links with a specific format of URLs. Can I use sizzle to evaluate a link's href attribute against a regular expression?

For example, can I do something like this:

var arrayOfLinks = Sizzle('a[HREF=[0-9]+$]');

to create an array of all links on the page whose URL ends in a number?


Solution

  • Give this a try. I've attempted to convert the jQuery regex selector that Kobi linked to into a Sizzle selector extension. Seems to work, but I haven't put it through a lot of testing.

    Sizzle.selectors.filters.regex = function(elem, i, match){ 
        var matchParams = match[3].split(',', 2);
        var attr = matchParams[0];
        var pattern = matchParams[1];
        var regex = new RegExp(pattern.replace(/^\s+|\s+$/g,''), 'ig');
        return regex.test(elem.getAttribute(attr));
    };
    

    In this case, your example would be written as:

    var arrayOfLinks = Sizzle('a:regex(href,[0-9]+$)');