Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find id in url

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?

like image 503
PeeHaa Avatar asked May 24 '11 22:05

PeeHaa


1 Answers

  1. Use window.location.pathname to retrieve the current path (excluding TLD).

  2. Use the JavaScript string match method.

  3. 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).

  4. 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.
    }
    
like image 149
Matt Avatar answered Oct 09 '22 04:10

Matt