Match elements via REGEXP in jQuery

Overview

This script allows REGEXP matching as part of jQuery's selector chains. It includes a plugin which provides a .regexp() method as part of a chain, and also an extension, which provides a :regexp pseudo selector.

Usage

Like other jQuery filters such as contains(), this REGEXP filter can be applied either as a pseudo selector or as a separate method of the chain. For the former, it is used as follows:

$('selector:regexp(/pattern/)') //etc

[imp] because arguments passed to pseudo-selectors (like our 'pattern' above) are sent as strings, any escaped characters must be double escaped. See example for more info.

Alternatively, the .regexp() method is used as follows:

$(selector).regexp(/pattern/) //etc

Note that, unlike with the pseudo selector technique, we are passing a genuine REGEXP object as the argument, so you do not have to double escape.

Example

  • PS3 games
  • PSP games
  • PS2 games
  • Nintendo Wii games
  • Nintendo DS games
  • XBox games

Click here to highlight Playstation rows

Clicking the above link highlights only the <li>s that match the selector. Here's the code behind the <a>'s onclick argument:

$('#productCats li:regexp(/^PS[\\d|P]{1}/)').css('color', '#f00')

This example uses the pseudo selector (note double escape), but we could achieve the same effect by using the equivalent method:

$('#productCats li').regexp(/^PS[\d|P]{1}/).css('color', '#f00')

Notes

Pseudo vs. method

Many jQuery filters can be implemented in either pseudo selector or method form. For example, there is both a :not pseudo selector and a not() method. Usually, the method alternative allows for more flexability as it accepts more arguments. Here, though, there is no difference in the workings of :regexp and .regexp().

regexp vs. contains

To match a simple string against the text of an element, rather than match a regular expression, you can use jQuery's in-built :contains pseudo selector or .contains() method.

posted @ 2010-06-27 13:53  架构师聊技术  阅读(273)  评论(0编辑  收藏  举报