Home > Net >  Cypress: extracting a portion of a string
Cypress: extracting a portion of a string

Time:08-26

I would appreciate some help. I am getting this text from a span: | 1-25 / 10.000 However, I would need to extract just 10.000 How could I split this string? Thank you very much in advance

   cy.get('.page-number > span')
           .then(($total) => {
              const total = $total.text();
              cy.log(total);
    })

CodePudding user response:

If you are only trying to assert that the 10.000 is in there, you could do a simple assertion like

cy.get(`.page-number > span`).contains('10.000').should("exist");
// or
cy.get(`.page-number > span`).contains('1-25 / 10.000').should("exist");

or if you want to make sure it's at the end of the string, using regex...

cy.get(`.page-number > span`).contains(/10\.000$/gmi).should("exist");

I fund using the simpler contains().should() assertions easier.

However if you want make the assertion within the promise, here are some things to keep in mind

  • the element passed from cy.get() will be a jQuery array. So running .text() on an Array will not work. You can specify using .eq(0) either inside or outside the promise, and once you have that text, you can do a regEx to retrieve value.
  • if you are using cy.get().then, it will give you the data at-the-time-of-operation. That is, it will not wait for the internal assertion to match. So if you are loading dynamic data, you might find that the text is not popupated yet

cy.get(".page-number > span").then(($total) => {
  const total = $total.eq(0).text(); // eq(0) inside promise
  cy.log(total.match(/([\d\.]*)$/gmi)[0]);
});

cy.get(".page-number > span")
  .eq(0) // eq(0) outside promise
  .then(($total) => {
    const total = $total.text();
    cy.log(total.match(/([\d\.]*)$/gmi)[0]);
  });
});

you can adjust the regex to more precisely match your needs. This one gets the last set of numbers (/d) or ([]) periods (./) before the end of the string ($). your html might include an extra space that's not visible, so you can add an optional space character (/s?): /([\d\.]*)\s?$/gmi

  • Related