jQuery :contains(regex)?

23,002

Try ,

var regex = new RegExp("[0-9]"); // expression here

$("#id a").filter(function () {
    return regex.test($(this).text()); 
});
Share:
23,002
Edge
Author by

Edge

Updated on April 08, 2020

Comments

  • Edge
    Edge about 4 years

    Is it possible to have a jQuery selector where the :contains() is a regular expression?

    I need to select an element where the innerHTML contains something findable through regex?

    I know it's a short question. My apologies.

    var t = $("#id a:containsRegex("/[0-9]/g")"); // Doesn't work
    
    • zerkms
      zerkms about 10 years
      Use .filter()
  • Tomalak
    Tomalak about 10 years
    @Pilot using innerText is wrong. Use $(this).text() instead.
  • Deepak Ingole
    Deepak Ingole about 10 years
    @Tomalak Updated..innerText is only valid for block elements ? M I right Master
  • ThiefMaster
    ThiefMaster about 10 years
    fyi you can use var regex = /[0-9]/; to make it more readable
  • Tomalak
    Tomalak about 10 years
    @Pilot No, innerTextis simply a proprietary DOM extension once invented by Microsoft. It should not be used as the default way to get text from an element, all modern browsers support the W3C standard textContent property.
  • Deepak Ingole
    Deepak Ingole about 10 years
    @Tomalak thanks for such a valuable comment..Much appreciated.
  • Muhammad Umer
    Muhammad Umer about 9 years
    just for others' reference filter is a jquery function not a native array filter function which i was mistaking it for.