Search code examples
textcypressextract

How to extract text from element having text in brackets in cypress i.e. test(5)


Can someone pls help in extracting text from element. Let us say we have element shown in page having text 'Test(10). How we can get text as o/p Test and 10 separately.

Thanks in advance!


Solution

  • You can use regex with name capture group.

    // example for 'Test(10)'
    cy.get('.element-selector')
      .invoke('text')
      .then(elText => {
        const matcher = /(?<text>test)\((?<number>\d+)\)/
        // extracts 'Test'
        const text = elText.match(matcher)?.groups?.text
        // extracts '10'
        const num = elText.match(matcher)?.groups?.num
      })