Reputation: 1999
I'm trying to test a location.pathname
. I'm passing a path to a function with regex. The path can be:
/dashboard
/dashboard/orders
And location.pathname
can be:
/dashboard
/dashboard/orders
/dashboard/orders/5ea5c95684c28d4b7ff688e1
/dashboard/orders/anyOtherId
What I want to do is when passing /dashboard/orders/5ea5c95684c28d4b7ff688e1
as location.pathname
it matches only with the path
/dashboard/orders
and not with /dashboard
.
Testing Regex in https://regexr.com/ I could make it work: \/dashboard\/*
, then I tried to implement it in javascript:
const matcher = new RegExp(`${path}\/*`)
matcher.test(location.pathname)
However, when I pass a path = /dashboard/orders
and location.pathname = /dashboard/orders/5ea5c95684c28d4b7ff688e1
it matches with /dashboard
and /dashboard/orders
. I need it to match only with /dashboard/orders
. /dashboard
must match only when path
is /dashboard
and location.pathname = /dashboard
.
How can I achieve this?
Thanks in advance
Edit: To be more clear, I need it to return true when path
is /dashboard/orders
and location.pathname
is /dashboard/orders
or /dashboard/orders/5ea5c95684c28d4b7ff688e1
.
But it must return false when path
is /dashboard
and location.pathname
is /dashboard/orders
or /dashboard/orders/5ea5c95684c28d4b7ff688e1
Upvotes: 1
Views: 224
Reputation: 785316
You can do a .replace
on location.pathname
to remove everything after 2nd path component and the just compare with the path
variable.
This solution should work for you:
path == location.pathname.replace(/^(\/dashboard\/[\w-]+)\/.*$/, '$1')
Upvotes: 1
Reputation: 3006
Here, you can use two different regexes. One regex -
"\/dashboard(\/)?$"
This will match "/dashboard"
and "/dashboard/"
Second regex -
"\/dashboard\/orders(\/[a-zA-Z0-9]*(\/)?)?$"
this will match
/dashboard/orders
/dashboard/orders/5ea5c95684c28d4b7ff688e1
/dashboard/orders/anyOtherId
/dashboard/orders/
/dashboard/orders/5ea5c95684c28d4b7ff688e1/
/dashboard/orders/anyOtherId/
Upvotes: 0