Anil Tiwari
Anil Tiwari

Reputation: 81

how to extract a portion of string in cypress

my problem statement is i am getting a text out of element something like this "stock name: apple inc","stock id: 23244"

i wanted to extract the text portion after ":" colon

my effort

cy.get(".column:nth-child(1)).find('li').eq(0).should('have.text','apple') //returning "stock name: apple inc" instead of "apple inc" only
cy.get(".column:nth-child(1)).find('li').eq(1).should('have.text','23244') //returning "stock id: 23244" instead of "23244" only

Upvotes: 1

Views: 3993

Answers (1)

Alapan Das
Alapan Das

Reputation: 18618

If you want to assert just the portion of the text you can use include.text instead of have.text

cy.get('.column:nth-child(1)').find('li').eq(0).should('include.text', 'apple')
cy.get('.column:nth-child(1)').find('li').eq(1).should('include.text', '23244')

You can use th split to extract the text and assert it as well.

cy.get('.column:nth-child(1)')
  .find('li')
  .eq(0)
  .invoke('text')
  .then((text) => {
    cy.log(text.split(':')[1]) //prints apple inc
    expect(text.split(':')[1]).to.equal('apple inc')
  })

cy.get('.column:nth-child(1)')
  .find('li')
  .eq(1)
  .invoke('text')
  .then((text) => {
    cy.log(text.split(':')[1]) //prints apple 23244
    expect(text.split(':')[1]).to.equal('23244')
  })

Upvotes: 3

Related Questions