skip to Main Content

Im new to cypress and im trying extract the number at the end of the following text into a variable. The element is "cy.get(‘:nth-child(3) > span’)" and the text is "1-44 of 44", i need to extract the number at the end after the of text and the value could be 1 to 1000

I took the code from another question but it doesnt answer my question as there is more that 1 number in the string.

I would really appreciate some help.

cy.get(':nth-child(3) > span').invoke('text').as('NoR')
  .then((NoR) => {
    var fullNoR = NoR;
    var pattern = /[0-9]+/g;
    var NewNOR = fullNoR.match(pattern);
    console.log(NewNOR);
  });

2

Answers


  1. parseInt(text.split("of")[1])
    

    You don’t have to parse the int out of it, but I would.

    Login or Signup to reply.
  2. The regex pattern is matching any number in the string "1-44 of 44", and there are three parts of the string that match.

    Your console.log(NewNOR) shows an array of these three numbers: ['1', '44', '44'], so you want the third one

    cy.get(':nth-child(3) > span').invoke('text')
    .then((text) => {
      const pattern = /[0-9]+/g
      const numbers = text.match(pattern)   // extracts 3 results
      console.log(numbers)                  //  ['1', '44', '44']
      const total = numbers[2]              // third result
      return +total                         // putting + in front to extract number
    })
    .should('eq', 44)
    

    enter image description here


    To just get the last digit, add $ to the pattern – this extracts just the digits at the end of the text.

    cy.get(':nth-child(3) > span').invoke('text')
    .then((text) => {
      const pattern = /[0-9]+$/g
      const total = text.match(pattern)[0]   // extracts 1 result only
      console.log(total)                     // '44'
      return +total                         
    })
    .should('eq', 44)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search