jQuery RegExp Selectors

March 16th, 2007 by Ralf S. Engelschall

I don’t know why jQuery doesn’t already provide support in its selector syntax for the Perl-style operators “=~” and “!~“, but I really wanted this feature for regular expression based matching of DOM node attribute value matching:

<div id="test1">TEST1</div>
<div id="test2">TEST2</div>
<script type="text/javascript">
  $("div[@id =~ '^test[0-9]$']").css("backgroundColor", "red");
</script>

This example colorizes the above two <div> nodes. Here is the patch for the jQuery sources which I’m using to add this functionality which is a “must have” for at least a Perl hacker like me ;-)

Index: src/selector/selector.js
--- src/selector/selector.js    (revision 1537)
+++ src/selector/selector.js    (working copy)
@@ -52,6 +52,8 @@
        "@": {
            "=": "z==m[4]",
            "!=": "z!=m[4]",
+           "=~": "z.match(RegExp(m[4]))!=null",
+           "!~": "z.match(RegExp(m[4]))==null",
            "^=": "z&&!z.indexOf(m[4])",
            "$=": "z&&z.substr(z.length - m[4].length,m[4].length)==m[4]",
            "*=": "z&&z.indexOf(m[4])>=0",
@@ -67,7 +69,7 @@
    // The regular expressions that power the parsing engine
    parse: [
        // Match: [@value='test'], [@foo]
-       /^\[ *(@)([a-z0-9_-]*) *([!*$^=]*) *('?"?)(.*?)\4 *\]/i,
+       /^\[ *(@)([a-z0-9_-]*) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/i,

        // Match: [div], [div p]
        /^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,

5 Responses to “jQuery RegExp Selectors”

  1. Carl Mueller says:

    Thanks! I was just looking at jQuery and was thinking the exact same thing. I mean, the language has regexp built in, and a core mission of regexp is SELECTING things…

    I was doing a search because OF COURSE it should be in there. Now I know a) it’s not, but b) it can be!

  2. wxl says:

    In the new version of JQuery since 1.1.3,the code must be changed to:

    type == “=” && z == m[5] ||
    type == “!=” && z != m[5] ||
    + (type == “=~” && z.match(RegExp(m[5]))!=null) ||
    + (type == “!~” && z.match(RegExp(m[5]))==null) ||
    type == “^=” && z && !z.indexOf(m[5]) ||
    type == “$=” && z.substr(z.length – m[5].length) == m[5] ||
    (type == “*=” || type == “~=”) && z.indexOf(m[5]) >= 0) ^ not )

  3. Brabby says:

    Hi, thanks for your functionality.
    I need to change the code to:
    “=~”: “z&&z.match(RegExp(m[4]))!=null”,
    “!~”: “z&&z.match(RegExp(m[4]))==null”,

    … because Firefox dont like the empty z

  4. Idetrorce says:

    very interesting, but I don’t agree with you

  5. Sebastian says:

    Hi,
    Have you managed to add this modification to 1.2.6 version of jQuery?

Leave a Reply