- Train of Thoughts - http://trainofthoughts.org/blog -

jQuery RegExp Selectors

Posted By Ralf S. Engelschall On Friday, March 16, 2007 @ 21:23 In Hacking,JavaScript | 5 Comments

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*\]/,

Article printed from Train of Thoughts: http://trainofthoughts.org/blog

URL to article: http://trainofthoughts.org/blog/2007/03/16/jquery-regexp-selector/

Copyright © Ralf S. Engelschall, All Rights Reserved.