Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

544
Views
How to take a part of a carrent url with cypress/javascript

how can i extract the id from this link ? .localhost/survey/20?vbpCategoryId

my code is:

cy.url().then(URL => {
  const current_url = URL.split('/');
  cy.log(current_url[nr]);

  cy.wrap(current_url[nr]).as('alias');

if it was between "/" it was easy but in this case it is between "/" and "?"

Thanks!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If your URL will always be formed similar to as you explained, we can use .split() and .pop() to easily get this ID.

.pop() takes the last item off of an array and returns it.

cy.url().then((url) => {
  const splitUrl = url.split('/');
  const ending = splitUrl.pop();
  const id = ending.split('?')[0];
  // code using id
})

I've been overly verbose in laying out each line, but you could theoretically combine it into one line as:

const id = url.split('/').pop().split('?')[0];

We could even simplify this a little bit, by using cy.location('pathname').

// assuming url is something like http://localhost:1234/survey/20?vbpCategoryId
cy.location('pathname').then((pathname) => {
  /** 
  * `pathname` yields us just the path, excluding the query parameters and baseUrl 
  * (in this case, `?vbpCategoryId` and `http://localhost:1234`), 
  * so we would have a string of `/survey/20`.
  */
  const id = pathname.split('/').pop();
});
about 4 years ago · Juan Pablo Isaza Report

0

Or you can use the .replace method with a regex to extract just the number from your url and then save it like this:

cy.url().then((URL) => {
  const id = +URL.replace(/[^0-9]/g, '') //Gets the id 20 and changes it to a number
  cy.wrap(id).as('urlId')
})

cy.get('@urlId').then((id) => {
  //access id here
})

In case you don't want the id to be converted into a number you can simply remove the + from URL.replace like this:

cy.url().then((URL) => {
  const id = URL.replace(/[^0-9]/g, '') //Gets the id 20
  cy.wrap(id).as('urlId')
})

cy.get('@urlId').then((id) => {
  //access id here
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!