Home > Back-end >  Using Regex in :contains jQuery Selector
Using Regex in :contains jQuery Selector

Time:03-09

I am trying to use regex in a :contains jQuery selector and I am having issues finding documentation that supports being able to do so. I have the DOM of a webpage loaded in the domContent variable and trying to find all lines that contain a webURL and log it to the console. I just want to output all instances of an email address listed in the DOM.

function doStuffWithDOM(domContent) {
      console.log($(domContent).filter(":contains('@')").text())
}

I want to replace the @ with a regex that outputs an email address based on the following regex \b[A-Z0-9._% -] @[A-Z0-9.-] \.[A-Z]{2,}\b

CodePudding user response:

You cannot use a regular expression using the :contains() selector.

According to the documentation, nowhere does it say a regex can be used, and the parameter text is just a plain string text:

text: A string of text to look for. It's case sensitive.

What you're looking for is using the filter's function parameter:

screenshot of function signature in documentation

This allows you to write custom code in the function (which can include a regular expression), and return true for elements that match the expression.

For more information, see "Using a Filter Function" section in the linked documentation.

  • Related