Home > Enterprise >  How to take a part of a carrent url with cypress/javascript
How to take a part of a carrent url with cypress/javascript

Time:03-31

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!

CodePudding user response:

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();
});

CodePudding user response:

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
})
  • Related