James Padolsey的jQuery正则表达式选择器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了James Padolsey的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)');

以上是关于James Padolsey的jQuery正则表达式选择器的主要内容,如果未能解决你的问题,请参考以下文章

正则表达式匹配 SSH url 部分

jQuery1990到2008年的正则表达式怎么写?

jQuery:包含(正则表达式)? [复制]

jquery 正则表达式

jquery常用正则表达式

为啥 jQuery 的电子邮件验证正则表达式如此简单?