1

I want to use Cypress and a regular expression to select an element which contains a certain text.

This get() command works:

cy.get('[data-cy=tile]').contains(new RegExp(myVar))

But this command fails:

cy.get('[data-cy=tile]:contains(' + new RegExp(myVar) + ')')

Is there a way to use a regular expression within jQuery :contains()?

ab22
  • 27
  • 5

2 Answers2

1

If you just want to use contains one way you can use the regex is to just use cy.contains(regex) as mentioned in the cypress docs.

Suppose you have an Html element like:

<ul>
  <li>apples</li>
  <li>oranges</li>
  <li>bananas</li>
</ul>

So you cypress code to fetch <li>bananas</li> using only Regex will be:

cy.contains(/^b\w+/)
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
1

I realize this doesn't answer your question about jQuery, but maybe this would accomplish what you're after?

From the Cypress documentation:

// yields <li>bananas</li>
cy.contains(/^b\w+/)
MetaWhirledPeas
  • 394
  • 1
  • 4