I have the following URL:
http://example.com/product/1/something/another-thing
Although it can also be:
http://test.example.com/product/1/something/another-thing
or
http://completelydifferentdomain.tdl/product/1/something/another-thing
And I want to get the number 1 (id) from the URL using Javascript.
The only thing that would always be the same is /product
. But I have some other pages where there is also /product
in the url just not at the start of the path.
What would the regex look like?
Use window.location.pathname
to
retrieve the current path (excluding
TLD).
Use the JavaScript string
match
method.
Use the regex /^\/product\/(\d+)/
to find a path which starts with /product/, then one or more digits (add i
right at the end to support case insensitivity).
Come up with something like this:
var res = window.location.pathname.match(/^\/product\/(\d+)/);
if (res.length == 2) {
// use res[1] to get the id.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With