Regex Selector for jQuery


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

check the original blogpost for more how-to examples


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. // USAGE
  15.  
  16. // Select all elements with an ID starting a vowel:
  17. $(':regex(id,^[aeiou])');
  18.  
  19. // Select all DIVs with classes that contain numbers:
  20. $('div:regex(class,[0-9])');
  21.  
  22. // Select all SCRIPT tags with a SRC containing jQuery:
  23. $('script:regex(src,jQuery)');
  24.  
  25. // Yes, I know the last example could be achieved with
  26. // CSS3 attribute selectors; it's just an example...

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.