Posted By

aelesbao on 01/27/11


Tagged

regex


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

virendrakryadav
wirenaught
jaypplr
rygiel


Regex Selector for jQuery by James Padolsey


 / Published in: jQuery
 

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

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.

  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)');

Report this snippet  

You need to login to post a comment.