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