jQuery selector regular expressions

JavascriptJqueryRegexJquery Selectors

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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

Solution 3 - Javascript

These can be helpful.

If you're finding by Contains then it'll be like this

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Starts With then it'll be like this

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Ends With then it'll be like this

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is not a given string

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which name contains a given word, delimited by spaces

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

Solution 4 - Javascript

If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ JQuery selector.

For example if your want to only select div with id starting with "abc", you can use:

$("div[id^='abc']")

A lot of very useful selectors to avoid use of regex can be find here: http://api.jquery.com/category/selectors/attribute-selectors/

Solution 5 - Javascript

var test = $('#id').attr('value').match(/[^a-z0-9 ]+/);

Here you go!

Solution 6 - Javascript

Add a jQuery function,

(function($){
    $.fn.regex = function(pattern, fn, fn_a){
        var fn = fn || $.fn.text;
        return this.filter(function() {
            return pattern.test(fn.apply($(this), fn_a));
        });
    };
})(jQuery);

Then,

$('span').regex(/Sent/)

will select all span elements with text matches /Sent/.

$('span').regex(/tooltip.year/, $.fn.attr, ['class'])

will select all span elements with their classes match /tooltip.year/.

Solution 7 - Javascript

ids and classes are still attributes, so you can apply a regexp attribute filter to them if you select accordingly. Read more here: http://rosshawkins.net/archive/2011/10/14/jquery-wildcard-selectors-some-simple-examples.aspx

Solution 8 - Javascript

$("input[name='option[colour]'] :checked ")

Solution 9 - Javascript

I'm just giving my real time example:

In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".

document.querySelectorAll("[id^='select2-qownerName_select-result']");

When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.

$("[id^='select2-qownerName_select-result']")

Solution 10 - Javascript

If you just want to select elements that contain given string then you can use following selector:

$(':contains("search string")')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoel CunninghamView Question on Stackoverflow
Solution 1 - JavascriptnickfView Answer on Stackoverflow
Solution 2 - JavascriptXenph YanView Answer on Stackoverflow
Solution 3 - JavascriptdnxitView Answer on Stackoverflow
Solution 4 - JavascriptNicolas JanelView Answer on Stackoverflow
Solution 5 - JavascriptKamil DąbrowskiView Answer on Stackoverflow
Solution 6 - Javascriptbrook hongView Answer on Stackoverflow
Solution 7 - JavascriptJānis ElmerisView Answer on Stackoverflow
Solution 8 - Javascriptirfan akhtarView Answer on Stackoverflow
Solution 9 - JavascriptVishnu Prasanth GView Answer on Stackoverflow
Solution 10 - JavascriptPrakash GPzView Answer on Stackoverflow