Cypress: Clicking on Element with Regex-Matched Text

How can I use Cypress to click on an element containing an exact match to a text using regular expressions?

Having worked extensively with Cypress, I’d be happy to provide some insights on this matter.

To achieve clicking on an element with an exact text match using regular expressions in Cypress, you can leverage the contains command coupled with a regular expression. This entails crafting a regular expression that accurately matches the specific text you’re targeting, enabling Cypress to pinpoint and interact with the desired element effectively.


cy.contains(/^Exact Text$/).click();

In Cypress, an alternative approach involves utilizing the data attribute associated with the element containing the precise text. By incorporating contains with the attribute selector, you can effortlessly locate and interact with the intended element, ensuring a seamless testing experience.


cy.contains('[data-testid="exact-text"]').click();

Employing contains() alongside other Cypress commands enables a comprehensive approach in identifying and manipulating elements with exact text matches. By combining contains() with assertions like should('be.visible'), you ensure not only the accurate identification of the element but also validate its visibility before initiating actions like clicking.


cy.contains(/^Exact Text$/).should('be.visible').click();