jQuery RegExp Selectors
March 16th, 2007 by Ralf S. EngelschallI 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*\]/,

![Ralf S. Engelschall's Train of Thoughts [.org]](http://trainofthoughts.org/blog/wp-content/themes/tot/tot-img/tot-2-CUT-typo-T.png)
May 9th, 2007 at 16:48 |
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!
July 19th, 2007 at 10:47 |
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 )
November 21st, 2007 at 16:54 |
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
December 15th, 2007 at 13:32 |
very interesting, but I don’t agree with you
October 10th, 2008 at 8:52 |
Hi,
Have you managed to add this modification to 1.2.6 version of jQuery?