Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector regular expressions

I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.

I have looked for this myself but have been unable to find information on the syntax and how to use it. Does anyone know where the documentation for the syntax is?

EDIT: The attribute filters allow you to select based on patterns of an attribute value.

like image 848
Joel Cunningham Avatar asked Oct 10 '08 05:10

Joel Cunningham


People also ask

Can I use regex in JQuery selector?

If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ JQuery selector. this won't work for case insensitive matches requirements.

How use contains in JQuery?

jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).


2 Answers

You can use the filter function to apply more complicated regex matching.

Here's an example which would just match the first three divs:

$('div')    .filter(function() {      return this.id.match(/abc+d/);    })    .html("Matched!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    <div id="abcd">Not matched</div>  <div id="abccd">Not matched</div>  <div id="abcccd">Not matched</div>  <div id="abd">Not matched</div>
like image 124
nickf Avatar answered Sep 20 '22 13:09

nickf


James Padolsey created a wonderful filter that allows regex to be used for selection.

Say you have the following div:

<div class="asdf"> 

Padolsey's :regex filter can select it like so:

$("div:regex(class, .*sd.*)") 

Also, check the official documentation on selectors.

UPDATE: : syntax Deprecation JQuery 3.0

Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:

jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {     return function (elem) {         var matchParams = expression.split(','),             validLabels = /^(data|css):/,             attr = {                 method: matchParams[0].match(validLabels) ?                     matchParams[0].split(':')[0] : 'attr',                 property: matchParams.shift().replace(validLabels, '')             },             regexFlags = 'ig',             regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);         return regex.test(jQuery(elem)[attr.method](attr.property));     } }); 
like image 24
Xenph Yan Avatar answered Sep 18 '22 13:09

Xenph Yan