Cypress - use of regular expression in 'contains' function returning no match

Viewed 7486

Cypress is supposed to allow regular expressions in its 'contains' function, but it is finding no match, whereas there are a lot of elements containing the search text. I have to put in the full name to allow it to find it - but I want to get all the elements with names starting with 'Tier2_Forest' not just one.

For instance, this works:

cy.get('#database-col')
  .find('div.el-row div.card header.card-header p.card-header-title')
  .contains('Tier2_Forest : Tier2_Forest_ManEvents')
  .as('dbCard');

But this doesn't:

cy.get('#database-col')
  .find('div.el-row div.card header.card-header p.card-header-title')
  .contains('Tier2_Forest')
  .as('dbCard');

Have also unsuccessfully tried it in the format recommended by Cypress for regex - i.e. line starts with that phrase: contains(/^Tier2_Forest/)

For some reason when I use contains('.db') it returns a list of elements containing '.db' at the end of their names - but I don't want those... Snippet of the generated DOM:


[Generated DOM]

2 Answers

I would say you are on the right track, but .contains(/^Tier2_Forest/) fails because the text is not at the beginning of the string, there is white space preceding it.

Just try .contains(/Tier2_Forest/)

or more precisely .contains(/\s*Tier2_Forest/)

where \s* matches any whitespace character (equal to [\r\n\t\f\v ])

Check it out in https://regex101.com

I had the same problem and I solved it like this:
It takes into account spaces and line breaks if there are any.

.contains(/^\s*\n?Tier2_Forest/) // check begins, with nothing before
.contains(/^\s*\n?Tier2_Forest : Forest Database\s*\n?$/) //exact same sentence, check nothing before, check nothing after
Related