Regex Selector for jQuery by James Padolsey


/ Published in: jQuery
Save to your folder(s)

The regular expression must be in non-literal notation; so replace all backslashes with two backslashes (e.g. ^\w+$ -> ^\\w+$).

All searches are case insensitive; you can change this by removing the ‘i’ flag in the plugin.


Copy this code and paste it in your HTML
  1. jQuery.expr[':'].regex = function(elem, index, match) {
  2. var matchParams = match[3].split(','),
  3. validLabels = /^(data|css):/,
  4. attr = {
  5. method: matchParams[0].match(validLabels) ?
  6. matchParams[0].split(':')[0] : 'attr',
  7. property: matchParams.shift().replace(validLabels,'')
  8. },
  9. regexFlags = 'ig',
  10. regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
  11. return regex.test(jQuery(elem)[attr.method](attr.property));
  12. }
  13.  
  14. /*********
  15.  * Usage
  16.  *********/
  17.  
  18. // Select all elements with an ID starting a vowel:
  19. $(':regex(id,^[aeiou])');
  20.  
  21. // Select all DIVs with classes that contain numbers:
  22. $('div:regex(class,[0-9])');
  23.  
  24. // Select all SCRIPT tags with a SRC containing jQuery:
  25. $('script:regex(src,jQuery)');
  26.  
  27. // Yes, I know the last example could be achieved with
  28. // CSS3 attribute selectors; it's just an example...
  29.  
  30. // Select all elements with a width between 100 and 300:
  31. $(':regex(css:width, ^[1-3]\\d{2}px$)');
  32.  
  33. // Select all NON block-level DIVs:
  34. $('div:not(:regex(css:display, ^block$))');
  35.  
  36. // Add data property to all images (just an example);
  37. $('img').each(function(){
  38. $(this).data('extension', $(this)[0].src.match(/\.(.{1,4})$/)[1]);
  39. });
  40.  
  41. // Select all images with PNG or JPG extensions:
  42. $('img:regex(data:extension, png|jpg)');

URL: http://james.padolsey.com/javascript/regex-selector-for-jquery/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.